-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod_parse.lua
More file actions
1229 lines (1069 loc) · 38.9 KB
/
Copy pathmod_parse.lua
File metadata and controls
1229 lines (1069 loc) · 38.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---Parse module for Corona SDK
-- @copyright develephant 2013-2015
-- @author Chris Byerley
-- @license MIT
-- @version 2.2.4
-- @see parse.com
local json = require("json")
local url = require("socket.url")
---Parse Class
-- @type Parse
local Parse =
{
--===========================================================================--
--== Options Start
--===========================================================================--
--Shows a clean table/object output
--in the main terminal.
showStatus = false, --default: false
--Show the http headers in the
--Parse response status output.
--showStatus must be 'true' as well.
showStatusHeaders = false, --default: false
--Output some basic information in
--a pop-up alert. Best for phone.
showAlert = false, --default: false
--Output the Parse response as
--JSON in the output console.
showJSON = false, --default: false
--Put 'results' outside of the 'response' key.
--By default when you recieve multiple records,
--the result set is put in a 'results' key on
--the 'response' object. To instead place the
--'results' key directly on the main object
--set this to 'false'. You would then access
--the results directly: `parse_response.results`
--as opposed to: `parse_response.response.results`
--Only works with multi-object response results.
resultsInResponse = true, --default: true
--===========================================================================--
--== Options Done. Nothing to see here...
--===========================================================================--
--Various initialization
endpoint = "https://api.parse.com/1/",
sessionToken = nil,
dispatcher = display.newGroup(),
--Set up clean request queue
requestQueue = {},
--Parse endpoints
NIL = nil,
ERROR = "ERROR",
EXPIRED = 101,
OBJECT = "classes",
USER = "users",
LOGIN = "login",
ANALYTICS = "events",
INSTALLATION = "installations",
CLOUD = "functions",
FILE = "files",
ROLE = "roles",
PUSH = "push",
--class constants
USER_CLASS = "_User",
ROLE_CLASS = "_Role",
--action constants
POST = "POST",
GET = "GET",
PUT = "PUT",
DELETE = "DELETE",
--upload types
TEXT = "text/plain",
PNG = "image/png",
JPG = "images/jpeg",
MOV = "video/quicktime",
M4V = "video/x-m4v",
MP4 = "video/mp4",
--set these with the init method
--not directly in the file.
appId = nil,
apiKey = nil
}
---Data Objects
-- @section data-oblects
---Create a new data object.
-- @string objClass The class object name.
-- @tab objDataTable The data table to create the object with.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onCreateObject( event )
-- if not event.error then
-- print( event.response.createdAt )
-- end
-- end
-- local dataTable = { ["score"] = 1200, ["cheatMode"] = false }
-- parse:createObject( "MyClass", dataTable, onCreateObject )
function Parse:createObject( objClass, objDataTable, _callback )
local uri = Parse:getEndpoint( Parse.OBJECT .. "/" .. objClass )
return self:sendRequest( uri, objDataTable, Parse.OBJECT, Parse.POST, _callback )
end
---Get a data object.
-- @string objClass The object class name.
-- @string objId The object ID.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onGetObject( event )
-- if not event.error then
-- print( event.response.objectId )
-- end
-- end
-- parse:getObject( "MyClass", "objectId", onGetObject )
function Parse:getObject( objClass, objId, _callback )
local uri = Parse:getEndpoint( Parse.OBJECT .. "/" .. objClass .. "/" .. objId )
return self:sendRequest( uri, {}, Parse.OBJECT, Parse.GET, _callback )
end
---Update a data object.
-- @string objClass The object class name.
-- @string objId The object ID.
-- @tab objDataTable The data table to update the object with.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onUpdateObject( event )
-- if not event.error then
-- print( event.response.updatedAt )
-- end
-- end
-- local dataTable = { ["score"] = 5200, ["cheatMode"] = true }
-- parse:updateObject( "MyClass", "objectId", dataTable, onUpdateObject )
function Parse:updateObject( objClass, objId, objDataTable, _callback )
local uri = Parse:getEndpoint( Parse.OBJECT .. "/" .. objClass .. "/" .. objId )
return self:sendRequest( uri, objDataTable, Parse.OBJECT, Parse.PUT, _callback )
end
---Delete a data object.
-- @string objClass The object class name.
-- @string objId The object ID.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onDeleteObject( event )
-- if not event.error then
-- print( event.response.value )
-- end
-- end
-- parse:deleteObject( "MyClass", "objectId", onDeleteObject )
function Parse:deleteObject( objClass, objId, _callback )
local uri = Parse:getEndpoint( Parse.OBJECT .. "/" .. objClass .. "/" .. objId )
return self:sendRequest( uri, {}, Parse.OBJECT, Parse.DELETE, _callback )
end
---Get objects.
-- @string objClass The object class name.
-- @tab queryTable A table based query.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onGetObjects( event )
-- if not event.error then
-- print( #event.results )
-- --OR
-- print( #events.response.results )
-- end
-- end
-- local queryTable = {
-- ["where"] = { ["score"] = { ["$lte"] = 2000 } }
-- }
-- parse:getObjects( "MyClass", queryTable, onGetObjects )
function Parse:getObjects( objClass, queryTable, _callback )
queryTable = queryTable or {}
local uri = Parse:getEndpoint( Parse.OBJECT .. "/" .. objClass )
return self:sendQuery( uri, queryTable, Parse.OBJECT, _callback )
end
---Link a data object to another object.
-- @string parseObjectType The Parse object type.
-- @string parseObjectId The Parse object ID.
-- @string linkField The name of the Parse `Pointer` field.
-- @string objTypeToLink The type of object that is being linked.
-- @string parseObjIdToLink The object id of the object being linked.
-- @func[opt] _callback The callback function.
-- @treturn[1] int The network request ID.
-- @treturn[2] nil No link was performed.
-- @usage
-- local function onLinkObject( event )
-- if not event.error then
-- print( event.response.updatedAt )
-- end
-- end
-- parse:linkObject( parse.USER, "user-object-id", "stats", "PlayerStat", "player-stat-object-id", onLinkFile )
function Parse:linkObject( parseObjectType, parseObjectId, linkField, objTypeToLink, parseObjIdToLink, _callback )
local linkField = linkField
local fileDataTable = { [linkField] = { ["className"] = objTypeToLink, ["objectId"] = parseObjIdToLink, ["__type"] = "Pointer" } }
if parseObjectType == Parse.USER then
return self:updateUser( parseObjectId, fileDataTable, _callback )
else
return self:updateObject( parseObjectType, parseObjectId, fileDataTable, _callback )
end
return nil
end
---Unlink a data object from another object.
-- @string parseObjectType The Parse object type.
-- @string parseObjectId The Parse object ID.
-- @string linkField The name the field with the link.
-- @func[opt] _callback The callback function.
-- @treturn[1] int The network request ID.
-- @treturn[2] nil No link was performed.
-- @usage
-- local function onUnlinkObject( event )
-- if not event.error then
-- print( event.response.updatedAt )
-- end
-- end
-- parse:unlinkObject( "Contact", "contact-object-id", "photo", onUnlinkObject )
function Parse:unlinkObject( parseObjectType, parseObjectId, linkField, _callback )
local linkField = linkField
local fileDataTable = { [linkField] = json.null }
if parseObjectType == Parse.USER then
return self:updateUser( parseObjectId, fileDataTable, _callback )
else
return self:updateObject( parseObjectType, parseObjectId, fileDataTable, _callback )
end
return nil
end
---Relations
-- @section relations
---Create a relationship.
-- @string objClass The object class name.
-- @string objId The object ID.
-- @string objField The Parse `Relation` field.
-- @tab objDataTable The data table to attach.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onAddRelation( event )
-- print( event.response.updatedAt )
-- end
-- local dataTbl = { { ["className"] = "Post", ["objectId"] = "postObjectId" } }
-- parse:createRelation( parse.USER, "userObjectId", "posts", dataTbl, onAddRelation )
function Parse:createRelation( objClass, objId, objField, objDataTable, _callback )
local uri
if objClass == Parse.USER then
uri = Parse:getEndpoint( Parse.USER .. "/" .. objId )
else
uri = Parse:getEndpoint( Parse.OBJECT .. "/" .. objClass .. "/" .. objId )
end
local objects = {}
for r=1, #objDataTable do
table.insert( objects,
{ ["__type"] = "Pointer", ["className"] = objDataTable[r].className, ["objectId"] = objDataTable[r].objectId }
)
end
local objField = objField
local relationDataTable = {
[ objField ] = { ["__op"] = "AddRelation", ["objects"] = objects }
}
return self:sendRequest( uri, relationDataTable, Parse.OBJECT, Parse.PUT, _callback )
end
---Remove a relationship.
-- @string objClass The object class name.
-- @string objId The object ID.
-- @string objField The object field.
-- @tab objDataTable The data table to remove.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onRemoveRelation( event )
-- print( event.response.updatedAt )
-- end
-- local dataTbl = { { ["className"] = "Post", ["objectId"] = "postObjectId" } }
-- parse:removeRelation( parse.USER, "userObjectId", "posts", dataTbl, onRemoveRelation )
function Parse:removeRelation( objClass, objId, objField, objDataTable, _callback )
local uri
if objClass == Parse.USER then
uri = Parse:getEndpoint( Parse.USER .. "/" .. objId )
else
uri = Parse:getEndpoint( Parse.OBJECT .. "/" .. objClass .. "/" .. objId )
end
local objects = {}
for r=1, #objDataTable do
table.insert( objects,
{ ["__type"] = "Pointer", ["className"] = objDataTable[r].className, ["objectId"] = objDataTable[r].objectId }
)
end
local objField = objField
local relationDataTable = {
[ objField ] = { ["__op"] = "RemoveRelation", ["objects"] = objects }
}
return self:sendRequest( uri, relationDataTable, Parse.OBJECT, Parse.PUT, _callback )
end
---File
-- @section files
---Upload a file.
-- Supports jpg, png, gif, mp4, mov, m4v
-- @tab fileMetaTable The file meta data table.
-- @string fileMetaTable.fileName The file name.
-- @param[opt=system.TemporaryDirectory] fileMetaTable.directory The base directory.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onUpload( event )
-- if event.name == "parseResponse" then --uploaded
-- print( event.response.name, event.response.url )
-- elseif event.name == "parseProgress" then --uploading
-- print( event.bytesTransferred )
-- end
-- end
-- parse:uploadFile( { ["filename"] = "photo.png", ["baseDir"] = system.DocumentsDirectory }, onUpload )
function Parse:uploadFile( fileMetaTable, _callback )
--filename, directory
assert( fileMetaTable.filename, "A filename is required in the meta table")
--V 1.64 fix by Alexander Sheety
local fileName = fileMetaTable.filename:gsub("%w*/","")
local directory = fileMetaTable.baseDir or system.TemporaryDirectory
--determine mime
local contentType = self:getMimeType( fileName )
local fileParams = self:newFileParams( contentType )
local q = {
requestId = network.upload(
self.endpoint .. self.FILE .. "/" .. fileName,
self.POST,
function(e) self:onResponse(e); end,
fileParams,
fileName,
directory,
contentType
),
requestType = self.FILE,
_callback = _callback,
}
table.insert( self.requestQueue, q )
return q.requestId
end
--V1.5 fix by https://bitbucket.org/neilhannah - Thanks!
---Link a file to another object.
-- @string parseObjectType The Parse object type.
-- @string parseObjectId The Parse object ID.
-- @string linkField The name of the linking field.
-- @string parseFileUriToLink The Parse supplied URI to the file.
-- @string parseFileUriToLinkUrl The Url to the file.
-- @func[opt] _callback The callback function.
-- @treturn[1] int The network request ID.
-- @treturn[2] nil No file was linked.
-- @usage
-- local function onLinkFile( event )
-- if not event.error then
-- print( event.response.updatedAt )
-- end
-- end
-- parse:linkFile( parse.USER, "user-object-id", "avatar", "1234567890abcdef-photo.png", onLinkFile )
function Parse:linkFile( parseObjectType, parseObjectId, linkField, parseFileUriToLink, parseFileUriToLinkUrl, _callback )
local linkField = linkField
local fileDataTable = { [linkField] = { ["name"] = parseFileUriToLink, ["url"] = parseFileUriToLinkUrl, ["__type"] = "File" } }
if parseObjectType == Parse.USER then
return self:updateUser( parseObjectId, fileDataTable, _callback )
else
return self:updateObject( parseObjectType, parseObjectId, fileDataTable, _callback )
end
return nil
end
---Unlink a file from another object.
--
-- NOTE: This does not delete the file from Parse.com, you must do that seperatly.
-- @string parseObjectType The name of the class that you want to unlink the resource from.
-- @string parseObjectId The objectId of the class object you want to unlink the resource from.
-- @string linkField The property (col) in the objClass that holds the link.
-- @func[opt] _callback The callback function.
-- @treturn[1] int The network request ID.
-- @treturn[2] nil No file was linked.
-- @usage
-- local function onUnlinkFile( event )
-- if not event.error then
-- print( event.response.updatedAt )
-- end
-- end
-- parse:unlinkFile( "Contact", "contact-object-id", "photo", onUnlinkFile )
function Parse:unlinkFile( parseObjectType, parseObjectId, linkField, _callback )
local linkField = linkField
local fileDataTable = { [linkField] = json.null }
if parseObjectType == Parse.USER then
return self:updateUser( parseObjectId, fileDataTable, _callback )
else
return self:updateObject( parseObjectType, parseObjectId, fileDataTable, _callback )
end
return nil
end
---Delete a file.
-- This method is depreciated. **Do Not Use.**
-- You should not disclose your master key in an application.
function Parse:deleteFile( parseFileName, parseMasterKey, _callback )
assert( parseMasterKey, "Parse Master Key is required to delete a file.")
local uri = Parse.endpoint .. Parse.FILE .. "/" .. parseFileName
return self:sendRequest( uri, {}, Parse.FILE, Parse.DELETE, _callback, parseMasterKey )
end
---Parse API BATCH
-- @todo Add the batch processing
---User
-- @section User
---Create a new User object.
-- @tab objDataTable The user data.
-- @func[opt] _callback The callback function.
-- @treturn int Returns a network ID.
-- @usage
-- local function onCreateUser( event )
-- if not event.error then
-- print( event.response.createdAt )
-- end
-- end
-- local userDataTable = { ["username"] = "Chris", ["password"] = "strongpw" }
-- parse:createUser( userDataTable, onCreateUser )
function Parse:createUser( objDataTable, _callback )
local uri = Parse:getEndpoint( Parse.USER )
return self:sendRequest( uri, objDataTable, Parse.USER, Parse.POST, _callback )
end
---Gets a User object.
-- @string objId The User object ID.
-- @func[opt] _callback The callback function.
-- @treturn int Returns a network ID.
-- @usage
-- local function onGetUser( event )
-- if not event.error then
-- print( event.response.username )
-- end
-- end
-- parse:getUser( "objectId", onGetUser )
function Parse:getUser( objId, _callback )
local uri = Parse:getEndpoint( Parse.USER .. "/" .. objId )
return self:sendRequest( uri, {}, Parse.USER, Parse.GET, _callback )
end
---Get Users.
-- @tab queryTable A query table.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onGetUsers( event )
-- if not event.error then
-- print( #event.results )
-- --OR
-- print( #events.response.results )
-- end
-- end
-- local queryTable = {
-- ["where"] = { ["username"] = "Chris" },
-- ["limit"] = 5
-- }
-- parse:getUsers( queryTable, onGetUsers )
function Parse:getUsers( queryTable, _callback )
queryTable = queryTable or {}
local uri = Parse:getEndpoint( Parse.USER )
return self:sendQuery( uri, queryTable, Parse.OBJECT, _callback )
end
---Log in a User.
-- @tab objDataTable The data table.
-- @func[opt] _callback The callback function.
-- @treturn[1] int The network request ID.
-- @treturn[2] nil User was not logged in.
-- @usage
-- local function onLoginUser( event )
-- if not event.error then
-- print( event.response.sessionToken )
-- end
-- end
-- parse:loginUser( { ["username"] = "Chris", ["password"] = "strongpw" }, onLoginUser )
function Parse:loginUser( objDataTable, _callback )
local uri = nil
if objDataTable.authData == nil then
uri = Parse:getEndpoint( Parse.LOGIN )
return self:sendQuery( uri, objDataTable, Parse.LOGIN, _callback )
else --facebook/twitter/UUID login
uri = Parse:getEndpoint( Parse.USER )
return self:sendRequest( uri, objDataTable, Parse.USER, Parse.POST, _callback )
end
return nil
end
---Update the logged in User.
-- _MUST BE LOGGED IN FIRST WITH SESSION TOKEN_
-- @string objId The User object id.
-- @tab objDataTable The object data table.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
--local function onUpdateUser( event )
-- if not event.error then
-- print( event.response.updatedAt )
-- end
--end
--local dataTable = { ["password"] = "newpassword" }
--parse:updateUser( "objectId", dataTable, onUpdateUser )
function Parse:updateUser( objId, objDataTable, _callback )
assert( self.sessionToken, "User must be logged in first, sessionToken cannot be nil.")
local uri = Parse:getEndpoint( Parse.USER .. "/" .. objId )
return self:sendRequest( uri, objDataTable, Parse.USER, Parse.PUT, _callback )
end
---Get the logged in User.
-- _MUST BE LOGGED IN FIRST WITH SESSION TOKEN_
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onGetMe( event )
-- if event.code == parse.EXPIRED then
-- print( "Session expired. Log in.")
-- else
-- print( "Hello", event.response.username )
-- end
-- end
-- parse:getUser( onGetMe )
function Parse:getMe( _callback )
assert( self.sessionToken, "User must be logged in first, sessionToken cannot be nil.")
local uri = Parse:getEndpoint( Parse.USER .. "/me" )
return self:sendRequest( uri, {}, Parse.USER, Parse.GET, _callback )
end
---Delete the logged in User.
-- _MUST BE LOGGED IN FIRST WITH SESSION TOKEN_
-- @string objId The object ID.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onDeleteUser( event )
-- if not event.error then
-- print( event.response.value )
-- end
-- end
-- parse:deleteUser( "objectId", onDeleteUser )
function Parse:deleteUser( objId, _callback )
assert( self.sessionToken, "User must be logged in first, sessionToken cannot be nil.")
local uri = Parse:getEndpoint( Parse.USER .. "/" .. objId )
return self:sendRequest( uri, {}, Parse.USER, Parse.DELETE, _callback )
end
---Request a lost password reset.
-- @string email The account email address.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onRequestPassword( event )
-- if not event.error then
-- print( event.response.value )
-- end
-- end
-- parse:requestPassword( "user@email.com", onRequestPassword )
function Parse:requestPassword( email, _callback )
local uri = Parse:getEndpoint( "requestPasswordReset" )
return self:sendRequest( uri, { ["email"] = email }, Parse.USER, Parse.POST, _callback )
end
---Analytics
-- @section analytics
---Application opened event.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onAppOpened( event )
-- if not event.error then
-- print( event.response.value )
-- end
-- end
-- parse:appOpened( onAppOpened )
function Parse:appOpened( _callback )
local uri = Parse:getEndpoint( Parse.ANALYTICS .. "/AppOpened" )
local requestParams = {}
return self:sendRequest( uri, { at = "" }, Parse.ANALYTICS, Parse.POST, _callback )
end
---Log a custom event.
-- @string eventType The event type.
-- @tab dimensionsTable The table of dimensions.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onLogEvent( event )
-- if not event.error then
-- print( event.response.value )
-- end
-- end
-- parse:logEvent( "Error", { ["type"] = "login" }, onLogEvent )
function Parse:logEvent( eventType, dimensionsTable, _callback )
dimensionsTable = dimensionsTable or {}
local uri = Parse:getEndpoint( Parse.ANALYTICS .. "/" .. eventType )
local requestParams = {
["dimensions"] = dimensionsTable
}
return self:sendRequest( uri, requestParams, Parse.ANALYTICS, Parse.POST, _callback )
end
---Roles
-- @section roles
---Create a new role.
-- @tab objDataTable The object data.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onCreateRole( event )
-- if not event.error then
-- print( event.response.createdAt )
-- end
-- end
-- local roleDataTable = { ["name"] = "Admins", ["ACL"] = { ["*"] = { ["read"] = true } } }
-- parse:createRole( roleDataTable, onCreateRole )
function Parse:createRole( objDataTable, _callback )
local uri = Parse:getEndpoint( Parse.ROLE )
return self:sendRequest( uri, objDataTable, Parse.ROLE, Parse.POST, _callback )
end
---Retrieve a role.
-- @string objId The object ID.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onGetRole( event )
-- if not event.error then
-- print( event.response.ACL["*"]["read"] )
-- end
-- end
-- parse:getRole( "objectId", onGetRole )
function Parse:getRole( objId, _callback )
local uri = Parse:getEndpoint( Parse.ROLE .. "/" .. objId )
return self:sendRequest( uri, {}, Parse.ROLE, Parse.GET, _callback )
end
---Push
-- @section push
-- Special thanks Ed Moyse https://bitbucket.org/edmoyse.
---Send a push message.
--
-- __NOTE: This will only work on iOS devices.__
-- @tab objDataTable The object data table for the Push message.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onSendPush(event)
-- if not event.error then
-- print(event.response)
-- end
-- end
-- local pushDataTable = {
-- ["where"] = {["channels"] = "", ["deviceType"] = "ios", ["userId"] = "objectId"},
-- ["data"] = {["alert"] = "Collect your FREE cookies!"}
-- }
-- parse:sendPush( pushDataTable, onSendPush )
function Parse:sendPush(objDataTable, _callback)
local uri = Parse:getEndpoint( Parse.PUSH )
return self:sendRequest( uri, objDataTable, Parse.PUSH, Parse.POST, _callback )
end
---Installations
-- @section installations
---Create a new installation.
-- @tab objDataTable The data table.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onInstallation( event )
-- if not event.error then
-- print( event.response.value )
-- end
-- end
-- local installationDataTable = {
-- ["deviceType"] = "ios",
-- ["deviceToken"] = "device-token",
-- ["channels"] = { "" },
-- }
-- parse:createInstallation( installationDataTable, onInstallation )
function Parse:createInstallation( objDataTable, _callback )
local uri = Parse:getEndpoint( Parse.INSTALLATION )
return self:sendRequest( uri, objDataTable, Parse.INSTALLATION, Parse.POST, _callback ) --returns requestId
end
---Update an installation.
-- @string objId The object ID.
-- @tab objDataTable The data table.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onUpdateInstallation( event )
-- if not event.error then
-- print( event.response.value )
-- end
-- end
-- local installationDataTable = {
-- ["channels"] = { "aNewChannel" },
-- }
-- parse:updateInstallation( installationId, installationDataTable, onUpdateInstallation )
function Parse:updateInstallation( objId, objDataTable, _callback )
local uri = Parse:getEndpoint( Parse.INSTALLATION .. "/" .. objId )
return self:sendRequest( uri, objDataTable, Parse.INSTALLATION, Parse.PUT, _callback ) --returns requestId
end
---Get an installation.
-- @string objId The object ID.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
function Parse:getInstallation( objId, _callback )
local uri = Parse:getEndpoint( Parse.INSTALLATION .. "/" .. objId )
return self:sendRequest( uri, {}, Parse.INSTALLATION, Parse.GET, _callback ) --returns requestId
end
---Cloud
-- @section cloud
---Run cloud code.
-- @string functionName The function name.
-- @tab functionParams A table of parameters.
-- @func[opt] _callback The callback function.
-- @treturn int The network request ID.
-- @usage
-- local function onRun( event )
-- if not event.error then
-- print( event.response.value )
-- end
-- end
-- parse:run( "Hello", { ["name"] = "Chris" }, onRun )
function Parse:run( functionName, functionParams, _callback )
functionParams = functionParams or {[""] = ""}
local uri = Parse:getEndpoint( Parse.CLOUD .. "/" .. functionName )
return self:sendRequest( uri, functionParams, Parse.CLOUD, Parse.POST, _callback ) --returns requestId
end
---------------------------------------------------------------------
-- Parse Module Internals
---------------------------------------------------------------------
---Build request parameters
-- @local
function Parse:buildRequestParams( withDataTable, masterKey )
local postData = json.encode( withDataTable )
return self:newRequestParams( postData, masterKey ) --for use in a network request
end
function Parse:sendRequest( uri, requestParamsTbl, requestType, action, _callback, masterKey )
local requestParams = self:buildRequestParams( requestParamsTbl, masterKey )
requestType = requestType or Parse.NIL
action = action or Parse.POST
local q = {
requestId = network.request( uri, action, function(e) Parse:onResponse(e); end, requestParams ),
requestType = requestType,
_callback = _callback,
}
table.insert( self.requestQueue, q )
return q.requestId
end
-- QUERIES --
function Parse:buildQueryParams( withQueryTable )
local uri = ""
for key, v in pairs( withQueryTable ) do
if uri ~= "" then
uri = uri .. "&"
end
local value = v
if key == "where" then
value = url.escape( json.encode( v ) )
end
uri = uri .. tostring( key ) .. "=" .. value
end
return self:newRequestParams( uri ) --for use in a network request
end
function Parse:sendQuery( uri, queryParamsTbl, requestType, _callback )
local requestParams = self:buildQueryParams( queryParamsTbl )
requestType = requestType or Parse.NIL
--action = action or Parse.GET
local queryUri = uri .. "?" .. requestParams.body
queryUri = string.gsub( queryUri, "%s+", '%20' )
local q = { requestId = network.request( queryUri, Parse.GET, function(e) Parse:onResponse(e); end, requestParams ),
requestType = requestType,
_callback = _callback,
}
table.insert( self.requestQueue, q )
return q.requestId
end
-- FILES --
function Parse:buildFileParams( withDataTable )
local postData = json.encode( withDataTable )
return self:newRequestParams( postData ) --for use in a network request
end
function Parse:sendFile( uri, requestParamsTbl, requestType, action )
local requestParams = self:buildRequestParams( requestParamsTbl )
requestType = requestType or Parse.NIL
action = action or Parse.POST
local q = { requestId = network.request( uri, action, function(e) Parse:onResponse(e); end, requestParams ), requestType = requestType }
table.insert( self.requestQueue, q )
return q.requestId
end
---Session
-- @section session
---Set the Parse provided sessionToken for all future calls that require it.
--
-- NOTE: The sessionToken is automatically set when you log a user in through Parse.
-- @string sessionToken The session token ID.
-- @treturn string The session token.
-- @usage
-- parse:setSessionToken( sessionToken )
function Parse:setSessionToken( sessionToken )
self.sessionToken = sessionToken
return self.sessionToken
end
---Returns the Parse sessionToken that is currently set.
-- @treturn string sessionToken The session token.
-- @usage
-- local sessionToken = parse:getSessionToken()
function Parse:getSessionToken()
return self.sessionToken
end
---Clears the Parse sessionToken.
--
-- NOTE: This does not clear or reset a user session with Parse, it only clears the sessionToken internally, in case you need to apply a new sessionToken.
-- @usage
-- parse:clearSessionToken()
function Parse:clearSessionToken()
self.sessionToken = nil
end
--======================================================================--
--== RESPONSE
--======================================================================--
function Parse:_debugOutput( e )
--== Show JSON flag
if self.showJSON then
if e.response ~= nil then
print( json.encode( e.response ) )
end
end
--== Show Status flag
if self.showStatus then
if e ~= nil then
if type(e) == 'table' then
self:printTable( e )
else
print('non-table response')
end
end
end
--== Show Alert flag
if self.showAlert then
local msg = string.format( "Net Status: %d \n", e.httpStatusCode )
--check error
if e.error then
msg = msg .. string.format( "Parse Code: %d \n", e.code )
if e.error then
msg = msg .. string.format( "Error: %s", e.error )
end
else
msg = "Parse action was successful!"
end
native.showAlert( "Parsed!", msg, { "OK" } )
end
end
--== Parse response handler
--== proceed with caution...
function Parse:onResponse( event )
if event.phase == "ended" then
-- Table to hold event response data
local response_data =
{
bytesEstimated = event.bytesEstimated,
bytesTransferred = event.bytesTransferred,
isError = event.isError, --Network error
requestId = event.requestId,
response = event.response,
responseHeaders = event.responseHeaders,
responseType = event.responseType,
status = event.status, --Network call status
url = event.url --The original requested url
}
-- Table for return_data, initialized
local return_data =
{
--Name of the return event
name = "parseResponse",
--The Parse request "type" - Parse.USER, etc.
requestType = nil, --Set later
response = nil, --Set later
results = nil, --Set later (maybe)
headers = response_data.responseHeaders or {}, --Incoming headers
code = nil, --Parse response code (-1 if no network)
error = nil, -- String final error code, can pass Parse errors
networkError = response_data.isError, -- 404 is not a networkError (Bool)
networkBytesTransferred = response_data.bytesTransferred or 0,
httpStatusCode = response_data.status or 0 -- http status code
}
--check showStatusHeaders flag
if self.showStatusHeaders == false then
return_data.headers = nil;
end
-- Start working with the response
-- first checking for Parse errors
local HAS_ERROR = false
if response_data and return_data then
-- Make sure we something to work with, or else.
assert(response_data, "response_data table missing.")
assert(return_data, "return_data table missing.")
local response_chk = json.decode( response_data.response )
--Check for Parse error in decoded response
if response_chk and type( response_chk ) == 'table' then
if response_chk.error then
return_data.error = response_chk.error