post.go 13.8 KB
Newer Older
Lukas Matt's avatar
Lukas Matt committed
1 2
package controllers
//
Lukas Matt's avatar
Lukas Matt committed
3
// GangGo API Library
Lukas Matt's avatar
Lukas Matt committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Copyright (C) 2017 Lukas Matt <lukas@zauberstuhl.de>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

import (
Lukas Matt's avatar
Lukas Matt committed
21
  "time"
Lukas Matt's avatar
Lukas Matt committed
22
  "github.com/revel/revel"
23
  "strconv"
24
  apiHelpers "gopkg.in/ganggo/api.v0/app/helpers"
Lukas Matt's avatar
Lukas Matt committed
25
  "gopkg.in/ganggo/ganggo.v0/app/helpers"
26 27 28
  "gopkg.in/ganggo/ganggo.v0/app/models"
  "gopkg.in/ganggo/ganggo.v0/app/jobs"
  federation "gopkg.in/ganggo/federation.v0"
29
  "net/http"
Lukas Matt's avatar
Lukas Matt committed
30 31
)

32 33 34 35 36
/**
 * @apiDefine Posts Posts endpoint
 *
 * Viewing, creating and deleting Post structures
 */
37
type ApiPost struct {
Lukas Matt's avatar
Lukas Matt committed
38
  *revel.Controller
39 40

  ApiHelper
Lukas Matt's avatar
Lukas Matt committed
41 42
}

43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
/**
 * @api {get} /posts Fetch all posts
 * @apiName ApiPost.Index
 * @apiGroup Posts
 *
 * @apiParam {String} access_token Oauth access token
 * @apiParam {Number} [offset] Post offset for database
 * @apiParam {String} [fields] Display only specific fields, e.g. fields=ID,Person(ID:Profile(ID:ImageUrl))
 * @apiParam {Number} [visibility] 0 = all posts, 1 = public posts, 2 private posts
 *
 * @apiSuccess {Array} Comments Comments related to the post
 * @apiSuccess {String} CreatedAt Timestamp of creation
 * @apiSuccess {String} Guid Unique global ID
 * @apiSuccess {Number} ID Unique database ID
 * @apiSuccess {Hash} Person Author of post
 * @apiSuccess {Number} PersonID Author database ID
 * @apiSuccess {String} ProviderName Provider
 * @apiSuccess {Boolean} Public Is it a public or private post
 * @apiSuccess {String} Text Post content
 * @apiSuccess {String} Type Entity type e.g. StatusMessage
 * @apiSuccess {String} UpdatedAt Timestamp of last replacment
 *
65
 * @apiSuccessExample {json} Success-Response
66 67 68 69 70 71 72 73 74
 *     HTTP/1.1 200 OK
 *     {
 *       "0": {
 *              "Guid": "5b5d5b4f7044e3444db73504e8b08be8",
 *              "ID": 20,
 *              "Text": "hi whats up?\r\n\r\n"
 *            }
 *     }
 *
75
 * @apiError (Errors) {String} error Contains the recent error message
76
 *
77 78
 * @apiErrorExample {json} Unauthorized
 *     HTTP/1.1 401 Unauthorized
79
 *     {
80
 *       "error": "[...]"
81
 *     }
82
 *
83 84
 * @apiErrorExample {json} NotFound
 *     HTTP/1.1 404 Not Found
85 86 87 88
 *     {
 *       "error": "[...]"
 *     }
 *
89
 */
90
func (p ApiPost) Index() revel.Result {
Lukas Matt's avatar
Lukas Matt committed
91 92
  var (
    offset int
93
    fields string
94
    visibility int
Lukas Matt's avatar
Lukas Matt committed
95 96 97 98
    posts models.Posts
  )

  p.Params.Bind(&offset, "offset")
99
  p.Params.Bind(&fields, "fields")
100
  p.Params.Bind(&visibility, "visibility")
101

102
  var err error
103
  if visibility == 0 {
104
    err = posts.FindAll(p.CurrentUser.ID, offset)
105 106 107
  } else if visibility == 1 {
    err = posts.FindAllPublic(offset)
  } else if visibility == 2 {
108
    err = posts.FindAllPrivate(p.CurrentUser.ID, offset)
109
  }
110

Lukas Matt's avatar
Lukas Matt committed
111
  if err != nil {
112 113
    p.Log.Error(TAG, "db", err, "api", ERR_NOT_FOUND)
    return p.ApiError(http.StatusNotFound, ERR_NOT_FOUND)
Lukas Matt's avatar
Lukas Matt committed
114 115
  }

116 117
  return p.RenderJSON(
    apiHelpers.SelectStructFields(posts, fields))
Lukas Matt's avatar
Lukas Matt committed
118 119
}

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
/**
 * @api {post} /posts Create a new post
 * @apiName ApiPost.Create
 * @apiGroup Posts
 *
 * @apiParam {String} access_token Oauth access token
 * @apiParam {String} aspectID=0 Needs an aspectID if you want to post privately
 * @apiParam {String} post The actual post message
 * @apiParam {String} [fields] Display only specific fields, e.g. fields=ID,Person(ID:Profile(ID:ImageUrl))
 *
 * @apiSuccess {Array} Comments Comments related to the post
 * @apiSuccess {String} CreatedAt Timestamp of creation
 * @apiSuccess {String} Guid Unique global ID
 * @apiSuccess {Number} ID Unique database ID
 * @apiSuccess {Hash} Person Author of post
 * @apiSuccess {Number} PersonID Author database ID
 * @apiSuccess {String} ProviderName Provider
 * @apiSuccess {Boolean} Public Is it a public or private post
 * @apiSuccess {String} Text Post content
 * @apiSuccess {String} Type Entity type e.g. StatusMessage
 * @apiSuccess {String} UpdatedAt Timestamp of last replacment
 *
142
 * @apiSuccessExample {json} Success-Response
143 144 145 146 147 148 149
 *     HTTP/1.1 200 OK
 *     {
 *       "Guid": "5b5d5b4f7044e3444db73504e8b08be8",
 *       "ID": 20,
 *       "Text": "hi whats up?\r\n\r\n"
 *     }
 *
150
 * @apiError (Errors) {String} error Contains the recent error message
151
 *
152 153
 * @apiErrorExample {json} BadRequest
 *     HTTP/1.1 400 Bad Request
154
 *     {
155
 *       "error": "[...]"
156
 *     }
157 158 159 160 161 162 163 164 165 166 167 168 169
 *
 * @apiErrorExample {json} Unauthorized
 *     HTTP/1.1 401 Unauthorized
 *     {
 *       "error": "[...]"
 *     }
 *
 * @apiErrorExample {json} ServerError
 *     HTTP/1.1 500 Internal Server Error
 *     {
 *       "error": "[...]"
 *     }
 *
170
 */
171
func (p ApiPost) Create() revel.Result {
Lukas Matt's avatar
Lukas Matt committed
172 173
  var (
    post models.Post
Lukas Matt's avatar
Lukas Matt committed
174
    postText, fields string
Lukas Matt's avatar
wip  
Lukas Matt committed
175
    aspectID, eventID uint
Lukas Matt's avatar
Lukas Matt committed
176 177 178
  )

  p.Params.Bind(&postText, "post")
Lukas Matt's avatar
Lukas Matt committed
179
  p.Params.Bind(&fields, "fields")
180
  p.Params.Bind(&aspectID, "aspectID")
Lukas Matt's avatar
wip  
Lukas Matt committed
181
  p.Params.Bind(&eventID, "eventID")
Lukas Matt's avatar
Lukas Matt committed
182

183 184 185
  if apiHelpers.EmptyString(postText) {
    p.Log.Error(TAG, "api", ERR_EMPTY_STRING)
    return p.ApiError(http.StatusBadRequest, ERR_EMPTY_STRING)
186 187
  }

Lukas Matt's avatar
Lukas Matt committed
188 189 190
  // create post
  guid, err := helpers.Uuid()
  if err != nil {
191 192
    p.Log.Error(TAG, "db", err, "api", ERR_SERVER)
    return p.ApiError(http.StatusInternalServerError, ERR_SERVER)
Lukas Matt's avatar
Lukas Matt committed
193 194
  }

Lukas Matt's avatar
wip  
Lukas Matt committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
  var entityEvent *federation.EntityEvent
  if eventID > 0 {
    var event models.CalendarEvent
    err = event.FindByUserAndID(p.CurrentUser, eventID)
    if err != nil {
      p.Log.Error(TAG, "db", err, "api", ERR_NOT_FOUND)
      return p.ApiError(http.StatusNotFound, ERR_NOT_FOUND)
    }

    var start, end federation.Time
    start.New(event.Start)
    end.New(event.End)

    entityEvent = &federation.EntityEvent{
      Author: event.Person.Profile.Author,
      Guid: event.Guid,
      Summary: event.Summary,
      Start: start,
      End: &end,
      AllDay: event.AllDay,
      Description: event.Description,
      Location: &federation.EntityLocation{
        // XXX we do not handle this right now
        Lat: "0.0", Lng: "0.0",
        Address: event.Location,
      },
    }
  }

Lukas Matt's avatar
Lukas Matt committed
224
  entity := federation.EntityStatusMessage{
225
    Text: postText,
226
    Author: p.CurrentUser.Person.Author,
Lukas Matt's avatar
Lukas Matt committed
227 228 229
    Guid: guid,
    ProviderName: "GangGo",
    Public: true,
Lukas Matt's avatar
wip  
Lukas Matt committed
230
    Event: entityEvent,
Lukas Matt's avatar
Lukas Matt committed
231
  }
Lukas Matt's avatar
Lukas Matt committed
232
  entity.CreatedAt.New(time.Now())
233 234 235 236
  // this one is a private message
  if aspectID > 0 {
    entity.Public = false
  }
Lukas Matt's avatar
Lukas Matt committed
237 238

  // save post locally
239
  err = post.Create(&entity)
Lukas Matt's avatar
Lukas Matt committed
240
  if err != nil {
241 242
    p.Log.Error(TAG, "db", err, "api", ERR_SERVER)
    return p.ApiError(http.StatusInternalServerError, ERR_SERVER)
Lukas Matt's avatar
Lukas Matt committed
243 244
  }

245 246 247 248 249
  if entity.Public == false {
    // this is required for mapping
    // posts to the author
    shareable := models.Shareable{
      ShareableID: post.ID,
250
      UserID: p.CurrentUser.ID,
251 252
      ShareableType: models.ShareablePost,
    }; if err := shareable.Create(); err != nil {
253 254
      p.Log.Error(TAG, "db", err, "api", ERR_SERVER)
      return p.ApiError(http.StatusInternalServerError, ERR_SERVER)
255 256
    }

257
    // create an aspect visibility entry
258 259 260 261 262 263 264
    // the host has to remember the recipients
    visibility := models.AspectVisibility{
      ShareableID: post.ID,
      AspectID: aspectID,
      ShareableType: models.ShareablePost,
    }
    if err := visibility.Create(); err != nil {
265 266
      p.Log.Error(TAG, "db", err, "api", ERR_SERVER)
      return p.ApiError(http.StatusInternalServerError, ERR_SERVER)
267
    }
268 269
  }

Lukas Matt's avatar
Lukas Matt committed
270
  dispatcher := jobs.Dispatcher{
271
    User: p.CurrentUser,
272
    Message: entity,
273
    Model: post,
Lukas Matt's avatar
Lukas Matt committed
274 275 276
  }
  go dispatcher.Run()

Lukas Matt's avatar
Lukas Matt committed
277 278
  return p.RenderJSON(
    apiHelpers.SelectStructFields(post, fields))
Lukas Matt's avatar
Lukas Matt committed
279 280
}

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303


/**
 * @api {post} /posts/:guid Fetch a specific post
 * @apiName ApiPost.Show
 * @apiGroup Posts
 *
 * @apiParam {String} access_token Oauth access token
 * @apiParam {String} guid Unique global ID
 * @apiParam {String} [fields] Display only specific fields, e.g. fields=ID,Person(ID:Profile(ID:ImageUrl))
 *
 * @apiSuccess {Array} Comments Comments related to the post
 * @apiSuccess {String} CreatedAt Timestamp of creation
 * @apiSuccess {String} Guid Unique global ID
 * @apiSuccess {Number} ID Unique database ID
 * @apiSuccess {Hash} Person Author of post
 * @apiSuccess {Number} PersonID Author database ID
 * @apiSuccess {String} ProviderName Provider
 * @apiSuccess {Boolean} Public Is it a public or private post
 * @apiSuccess {String} Text Post content
 * @apiSuccess {String} Type Entity type e.g. StatusMessage
 * @apiSuccess {String} UpdatedAt Timestamp of last replacment
 *
304
 * @apiSuccessExample {json} Success-Response
305 306 307 308 309 310 311
 *     HTTP/1.1 200 OK
 *     {
 *       "Guid": "5b5d5b4f7044e3444db73504e8b08be8",
 *       "ID": 20,
 *       "Text": "hi whats up?\r\n\r\n"
 *     }
 *
312
 * @apiError (Errors) {String} error Contains the recent error message
313
 *
314 315
 * @apiErrorExample {json} Unauthorized
 *     HTTP/1.1 401 Unauthorized
316
 *     {
317
 *       "error": "[...]"
318
 *     }
319
 *
320 321
 * @apiErrorExample {json} NotFound
 *     HTTP/1.1 404 Not Found
322 323 324 325
 *     {
 *       "error": "[...]"
 *     }
 *
326
 */
327 328
func (p ApiPost) Show(guid string) revel.Result {
  var post models.Post
329 330 331
  var fields string

  p.Params.Bind(&fields, "fields")
332 333 334

  postID, err := strconv.ParseUint(guid, 10, 32);
  if err == nil {
335
    err = post.FindByIDAndUser(uint(postID), p.CurrentUser)
336
  } else {
337
    err = post.FindByGuidAndUser(guid, p.CurrentUser)
338
  }
Lukas Matt's avatar
Lukas Matt committed
339
  if err != nil {
340 341
    p.Log.Error(TAG, "db", err, "api", ERR_NOT_FOUND)
    return p.ApiError(http.StatusNotFound, ERR_NOT_FOUND)
Lukas Matt's avatar
Lukas Matt committed
342 343
  }

344 345
  return p.RenderJSON(
    apiHelpers.SelectStructFields(post, fields))
Lukas Matt's avatar
Lukas Matt committed
346 347
}

348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
/**
 * @api {delete} /posts/:guid Delete post/reshare
 * @apiName ApiPost.Delete
 * @apiGroup Posts
 *
 * @apiParam {String} access_token Oauth access token
 * @apiParam {String} guid Unique global ID
 *
 * @apiSuccessExample {json} Success-Response
 *     HTTP/1.1 200 OK
 *     {}
 *
 * @apiError (Errors) {String} error Contains the recent error message
 *
 * @apiErrorExample {json} BadRequest
 *     HTTP/1.1 400 BadRequest
 *     {
 *       "error": "[...]"
 *     }
 *
 * @apiErrorExample {json} Unauthorized
 *     HTTP/1.1 401 Unauthorized
 *     {
 *       "error": "[...]"
 *     }
 *
 * @apiErrorExample {json} NotFound
 *     HTTP/1.1 404 Not Found
 *     {
 *       "error": "[...]"
 *     }
 *
 */
func (p ApiPost) Delete(guid string) revel.Result {
  var post models.Post
  postID, err := strconv.ParseUint(guid, 10, 32);
  if err == nil {
    err = post.FindByIDAndUser(uint(postID), p.CurrentUser)
  } else {
    err = post.FindByGuidAndUser(guid, p.CurrentUser)
  }
  if err != nil {
    p.Log.Error(TAG, "db", err, "api", ERR_POST_NOT_FOUND)
    return p.ApiError(http.StatusNotFound, ERR_POST_NOT_FOUND)
  }

  if post.Person.ID == p.CurrentUser.Person.ID {
    entity := federation.EntityRetraction{
      Author: p.CurrentUser.Person.Author,
      TargetGuid: post.Guid,
      TargetType: models.ShareablePost,
    }
    dispatcher := jobs.Dispatcher{
      User: p.CurrentUser,
      Message: entity,
    }
    // NOTE relay to other hosts if we own this entity
    // should be done before we start deleting db records
    // thats why this call is synchron XXX we should
    // change that !
    dispatcher.Run()

    err = post.Delete()
    if err != nil {
      p.Log.Error(TAG, "db", err, "api", ERR_NOT_FOUND)
      return p.ApiError(http.StatusNotFound, ERR_NOT_FOUND)
    }
  } else {
    p.Log.Error(TAG, "api", ERR_BAD_REQUEST)
    return p.ApiError(http.StatusBadRequest, ERR_BAD_REQUEST)
  }
  return p.RenderJSON(struct{}{})
}

/**
 * @api {post} /posts/:guid/reshare Reshare a post
 * @apiName ApiPost.Reshare
 * @apiGroup Posts
 *
 * @apiParam {String} access_token Oauth access token
 * @apiParam {String} guid Unique global ID
 *
 * @apiSuccessExample {json} Success-Response
 *     HTTP/1.1 200 OK
 *     {}
 *
 * @apiError (Errors) {String} error Contains the recent error message
 *
 * @apiErrorExample {json} BadRequest
 *     HTTP/1.1 400 BadRequest
 *     {
 *       "error": "[...]"
 *     }
 *
 * @apiErrorExample {json} Unauthorized
 *     HTTP/1.1 401 Unauthorized
 *     {
 *       "error": "[...]"
 *     }
 *
 * @apiErrorExample {json} NotFound
 *     HTTP/1.1 404 Not Found
 *     {
 *       "error": "[...]"
 *     }
 *
 * @apiErrorExample {json} ServerError
 *     HTTP/1.1 500 Internal Server Error
 *     {
 *       "error": "[...]"
 *     }
 *
 */
func (p ApiPost) Reshare() revel.Result {
  var rootPost models.Post
  var rootGuid string

  p.Params.Bind(&rootGuid, "guid")

  postID, err := strconv.ParseUint(rootGuid, 10, 32);
  if err == nil {
    err = rootPost.FindByIDAndUser(uint(postID), p.CurrentUser)
  } else {
    err = rootPost.FindByGuidAndUser(rootGuid, p.CurrentUser)
  }
  if err != nil {
    p.Log.Error(TAG, "db", err, "api", ERR_POST_NOT_FOUND)
    return p.ApiError(http.StatusNotFound, ERR_POST_NOT_FOUND)
  }

  if rootPost.Person.ID == p.CurrentUser.Person.ID {
    p.Log.Error(TAG, "api", ERR_BAD_REQUEST)
    return p.ApiError(http.StatusBadRequest, ERR_BAD_REQUEST)
  }

  guid, err := helpers.Uuid()
  if err != nil {
    p.Log.Error(TAG, "db", err, "api", ERR_SERVER)
    return p.ApiError(http.StatusInternalServerError, ERR_SERVER)
  }

  entity := federation.EntityReshare{
    Author: p.CurrentUser.Person.Author,
    Guid: guid,
    RootAuthor: rootPost.Person.Author,
    RootGuid: rootPost.Guid,
  }
Lukas Matt's avatar
Lukas Matt committed
495
  entity.CreatedAt.New(time.Now())
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510

  var post models.Post
  err = post.Create(&entity)
  if err != nil {
    p.Log.Error(TAG, "db", err, "api", ERR_SERVER)
    return p.ApiError(http.StatusInternalServerError, ERR_SERVER)
  }

  dispatcher := jobs.Dispatcher{
    User: p.CurrentUser,
    Model: post,
    Message: entity,
  }
  go dispatcher.Run()
  return p.RenderJSON(post)
Lukas Matt's avatar
Lukas Matt committed
511
}