CCMain.m 256 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotosCameraUpload.h"
  26. #import "CCOfflineFileFolder.h"
  27. #import <OCCommunicationLib/OCNotifications.h>
  28. #import <OCCommunicationLib/OCNotificationsAction.h>
  29. #import <OCCommunicationLib/OCFrameworkConstants.h>
  30. #import "CTAssetCheckmark.h"
  31. #import "Nextcloud-Swift.h"
  32. #pragma GCC diagnostic ignored "-Wundeclared-selector"
  33. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  34. #define alertCreateFolder 1
  35. #define alertCreateFolderCrypto 2
  36. #define alertRename 3
  37. #define alertOfflineFolder 4
  38. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate>
  39. {
  40. CCMetadata *_metadataSegue;
  41. CCMetadata *_metadata;
  42. BOOL _isRoot;
  43. BOOL _isViewDidLoad;
  44. BOOL _isOfflineServerUrl;
  45. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  46. BOOL _isSelectedMode;
  47. NSMutableArray *_selectedMetadatas;
  48. NSMutableArray *_queueSelector;
  49. NSUInteger _numSelectedMetadatas;
  50. UIImageView *_ImageTitleHomeCryptoCloud;
  51. UIView *_reMenuBackgroundView;
  52. UITapGestureRecognizer *_singleFingerTap;
  53. NSString *_directoryGroupBy;
  54. NSString *_directoryOrder;
  55. NSUInteger _failedAttempts;
  56. NSDate *_lockUntilDate;
  57. NSString *_fatherPermission;
  58. UIRefreshControl *_refreshControl;
  59. UIDocumentInteractionController *_docController;
  60. CCHud *_hud;
  61. CCHud *_hudDeterminate;
  62. // Datasource
  63. CCSectionDataSource *_sectionDataSource;
  64. NSDate *_dateReadDataSource;
  65. // Search
  66. BOOL _isSearchMode;
  67. BOOL _reloadForcedFoderWhenSearchModeOff;
  68. NSString *_searchFileName;
  69. NSArray *_searchResultMetadatas;
  70. }
  71. @end
  72. @implementation CCMain
  73. #pragma --------------------------------------------------------------------------------------------
  74. #pragma mark ===== Init =====
  75. #pragma --------------------------------------------------------------------------------------------
  76. - (id)initWithCoder:(NSCoder *)aDecoder
  77. {
  78. if (self = [super initWithCoder:aDecoder]) {
  79. _directoryOrder = [CCUtility getOrderSettings];
  80. _directoryGroupBy = [CCUtility getGroupBySettings];
  81. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  82. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  83. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitleNOAnimation) name:@"setTitleCCMainNOAnimation" object:nil];
  84. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitleYESAnimation) name:@"setTitleCCMainYESAnimation" object:nil];
  85. }
  86. return self;
  87. }
  88. #pragma --------------------------------------------------------------------------------------------
  89. #pragma mark ===== View =====
  90. #pragma --------------------------------------------------------------------------------------------
  91. - (void)viewDidLoad
  92. {
  93. [super viewDidLoad];
  94. // init object
  95. _metadata = [CCMetadata new];
  96. _metadataSegue = [CCMetadata new];
  97. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  98. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  99. _selectedMetadatas = [NSMutableArray new];
  100. _queueSelector = [NSMutableArray new];
  101. _isViewDidLoad = YES;
  102. _fatherPermission = @"";
  103. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  104. _searchResultMetadatas = [NSArray new];
  105. _searchFileName = @"";
  106. // delegate
  107. self.tableView.delegate = self;
  108. self.tableView.tableFooterView = [UIView new];
  109. self.tableView.separatorColor = COLOR_SEPARATOR_TABLE;
  110. self.searchController.delegate = self;
  111. self.searchController.searchBar.delegate = self;
  112. [[CCNetworking sharedNetworking] settingDelegate:self];
  113. // Custom Cell
  114. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  115. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  116. // long press recognizer TableView
  117. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  118. [self.tableView addGestureRecognizer:longPressRecognizer];
  119. // Pull-to-Refresh
  120. [self createRefreshControl];
  121. // Register for 3D Touch Previewing if available
  122. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  123. {
  124. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  125. }
  126. // Back Button
  127. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  128. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_brandNavigationController] style:UIBarButtonItemStylePlain target:nil action:nil];
  129. // reMenu Background
  130. _reMenuBackgroundView = [[UIView alloc] init];
  131. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  132. // if this is not Main (the Main uses inizializeMain)
  133. if (_isRoot == NO && app.activeAccount.length > 0) {
  134. // Settings this folder & delegate & Loading datasource
  135. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  136. // Load Datasource
  137. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  138. // Read Folder
  139. [self readFolderWithForced:NO];
  140. }
  141. // Title
  142. [self setTitle];
  143. // List Transfers
  144. app.controlCenter = (CCControlCenter *)self.navigationController;
  145. // Search
  146. self.definesPresentationContext = YES;
  147. self.searchController.searchResultsUpdater = self;
  148. self.searchController.dimsBackgroundDuringPresentation = NO;
  149. self.tableView.tableHeaderView = self.searchController.searchBar;
  150. self.searchController.searchBar.barTintColor = COLOR_SEPARATOR_TABLE;
  151. [self.searchController.searchBar sizeToFit];
  152. if (_isRoot) self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  153. else self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  154. //self.searchController.searchBar.scopeButtonTitles = @[NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_all_folders_",nil)];
  155. }
  156. // Apparirà
  157. - (void)viewWillAppear:(BOOL)animated
  158. {
  159. [super viewWillAppear:animated];
  160. // test
  161. if (app.activeAccount.length == 0)
  162. return;
  163. // Settings this folder & delegate & Loading datasource
  164. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  165. [[CCNetworking sharedNetworking] settingDelegate:self];
  166. // Color
  167. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  168. [CCAspect aspectTabBar:self.tabBarController.tabBar hidden:NO];
  169. // Menu e Bar
  170. [self createReMainMenu];
  171. [self createReSelectMenu];
  172. if (_isSelectedMode)
  173. [self setUINavigationBarSelected];
  174. else [self setUINavigationBarDefault];
  175. // Plus Button
  176. [app plusButtonVisibile:true];
  177. }
  178. // E' arrivato
  179. - (void)viewDidAppear:(BOOL)animated
  180. {
  181. [super viewDidAppear:animated];
  182. // Active Main
  183. app.activeMain = self;
  184. // Test viewDidLoad
  185. if (_isViewDidLoad) {
  186. _isViewDidLoad = NO;
  187. } else {
  188. if (app.activeAccount.length > 0) {
  189. // Load Datasource
  190. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  191. // Read Folder
  192. [self readFolderWithForced:NO];
  193. }
  194. }
  195. // Title
  196. [self setTitle];
  197. // cancell Progress
  198. [self.navigationController cancelCCProgress];
  199. }
  200. - (void)viewWillDisappear:(BOOL)animated
  201. {
  202. [super viewWillDisappear:animated];
  203. // Close MainMenu & SelectMenu
  204. if (app.reMainMenu.isOpen || app.reSelectMenu.isOpen) {
  205. [app.reMainMenu close];
  206. [app.reSelectMenu close];
  207. }
  208. // Close Menu change user
  209. [CCMenu dismissMenu];
  210. }
  211. - (void)didReceiveMemoryWarning
  212. {
  213. [super didReceiveMemoryWarning];
  214. // Dispose of any resources that can be recreated.
  215. }
  216. - (BOOL)prefersStatusBarHidden
  217. {
  218. return NO;
  219. }
  220. // detect scroll for remove keyboard in search mode
  221. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  222. {
  223. if (_isSearchMode && scrollView == self.tableView) {
  224. [self.searchController.searchBar endEditing:YES];
  225. }
  226. }
  227. #pragma --------------------------------------------------------------------------------------------
  228. #pragma mark ===== Initizlize Mail =====
  229. #pragma --------------------------------------------------------------------------------------------
  230. - (void)initializeMain:(NSNotification *)notification
  231. {
  232. _directoryGroupBy = nil;
  233. _directoryOrder = nil;
  234. _dateReadDataSource = nil;
  235. // test
  236. if (app.activeAccount.length == 0)
  237. return;
  238. if ([app.listMainVC count] == 0 || _isRoot) {
  239. // This is Root
  240. _isRoot = YES;
  241. // Crypto Mode
  242. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  243. app.isCryptoCloudMode = NO;
  244. } else {
  245. app.isCryptoCloudMode = YES;
  246. }
  247. // go Home
  248. [self.navigationController popToRootViewControllerAnimated:NO];
  249. // Remove search mode
  250. [self cancelSearchBar];
  251. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  252. _isFolderEncrypted = NO;
  253. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  254. // add list
  255. [app.listMainVC setObject:self forKey:_serverUrl];
  256. // setting Networking
  257. [[CCNetworking sharedNetworking] settingDelegate:self];
  258. [[CCNetworking sharedNetworking] settingAccount];
  259. // populate shared Link & User variable
  260. [CCCoreData populateSharesVariableFromDBActiveAccount:app.activeAccount sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup];
  261. // Load Datasource
  262. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  263. // Load Folder
  264. [self readFolderWithForced:NO];
  265. // Load photo datasorce
  266. if (app.activePhotosCameraUpload)
  267. [app.activePhotosCameraUpload reloadDatasourceForced];
  268. // remove all of detail
  269. if (app.activeDetail)
  270. [app.activeDetail removeAllView];
  271. // remove all Notification Messages
  272. [app.listOfNotifications removeAllObjects];
  273. // home main
  274. app.homeMain = self;
  275. // Initializations
  276. [app applicationInitialized];
  277. } else {
  278. // reload datasource
  279. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  280. }
  281. }
  282. #pragma --------------------------------------------------------------------------------------------
  283. #pragma mark ===== AlertView =====
  284. #pragma --------------------------------------------------------------------------------------------
  285. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  286. {
  287. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  288. if (alertView.tag == alertCreateFolder && buttonIndex == 1) [self createFolder:[alertView textFieldAtIndex:0].text folderCameraUpload:NO];
  289. if (alertView.tag == alertCreateFolderCrypto && buttonIndex == 1) [self createFolderEncrypted:[alertView textFieldAtIndex:0].text];
  290. if (alertView.tag == alertRename && buttonIndex == 1) {
  291. if ([_metadata.model isEqualToString:@"note"]) {
  292. [self renameNote:_metadata fileName:[alertView textFieldAtIndex:0].text];
  293. } else {
  294. [self renameFile:_metadata fileName:[alertView textFieldAtIndex:0].text];
  295. }
  296. }
  297. if (alertView.tag == alertOfflineFolder && buttonIndex == 1) {
  298. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  299. NSString *dir = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  300. [[CCOfflineFileFolder sharedOfflineFileFolder] addOfflineFolder:dir];
  301. [self performSelector:@selector(reloadDatasource) withObject:nil];
  302. }
  303. }
  304. // accept only number char > 0
  305. - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
  306. {
  307. /* Retrieve a text field at an index -
  308. raises NSRangeException when textFieldIndex is out-of-bounds.
  309. The field at index 0 will be the first text field
  310. (the single field or the login field),
  311. The field at index 1 will be the password field. */
  312. /*
  313. 1> Get the Text Field in alertview
  314. 2> Get the text of that Text Field
  315. 3> Verify that text length
  316. 4> return YES or NO Based on the length
  317. */
  318. if (alertView.tag == alertOfflineFolder) return YES;
  319. else return ([[[alertView textFieldAtIndex:0] text] length]>0)?YES:NO;
  320. }
  321. #pragma --------------------------------------------------------------------------------------------
  322. #pragma mark ===== Graphic Window =====
  323. #pragma --------------------------------------------------------------------------------------------
  324. - (void)createRefreshControl
  325. {
  326. _refreshControl = [UIRefreshControl new];
  327. _refreshControl.tintColor = COLOR_REFRESH_CONTROL;
  328. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  329. [self setRefreshControl:_refreshControl];
  330. }
  331. - (void)deleteRefreshControl
  332. {
  333. [_refreshControl endRefreshing];
  334. self.refreshControl = nil;
  335. }
  336. - (void)refreshControlTarget
  337. {
  338. [self readFolderWithForced:YES];
  339. // Actuate `Peek` feedback (weak boom)
  340. AudioServicesPlaySystemSound(1519);
  341. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  342. }
  343. - (void)setTitle
  344. {
  345. // PopGesture in progress [swipe gesture to switch between views]
  346. if (app.controlCenter.isPopGesture)
  347. return;
  348. // Color text self.navigationItem.title
  349. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  350. if (_isSelectedMode) {
  351. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  352. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  353. self.navigationItem.titleView = nil;
  354. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  355. } else {
  356. // we are in home : LOGO BRAND
  357. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  358. self.navigationItem.title = nil;
  359. if ([app.reachability isReachable] == NO) _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:image_brandNavigationControllerOffline]];
  360. else _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:image_brandNavigationController]];
  361. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  362. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuChangeUser)];
  363. [singleTap setNumberOfTapsRequired:1];
  364. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  365. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  366. } else {
  367. BOOL isOfflineDirectory = [CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount];
  368. if (isOfflineDirectory) {
  369. self.navigationItem.titleView = [CCGraphics navigationBarTitle:_titleMain image:[UIImage imageNamed:image_offlineTitle] frame:self.navigationController.navigationBar.frame];
  370. } else
  371. self.navigationItem.title = _titleMain;
  372. }
  373. }
  374. }
  375. - (void)setTitleBackgroundTableView
  376. {
  377. if ([_sectionDataSource.allRecordsDataSource count] == 0) {
  378. [self setTitleBackgroundTableView:NSLocalizedString(@"_no_file_pull_down_", nil)];
  379. } else {
  380. [self setTitleBackgroundTableView:nil];
  381. }
  382. }
  383. - (void)setTitleBackgroundTableView:(NSString *)title
  384. {
  385. if (title) {
  386. // message if table is empty
  387. UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
  388. if ([app.reachability isReachable] == NO) {
  389. messageLabel.text = NSLocalizedString(@"_comm_erro_pull_down_", nil);
  390. messageLabel.textColor = COLOR_TEXT_NO_CONNECTION;
  391. messageLabel.font = [UIFont systemFontOfSize:14];
  392. } else {
  393. messageLabel.text = NSLocalizedString(title ,nil);
  394. messageLabel.textColor = [UIColor blackColor];
  395. messageLabel.font = [UIFont systemFontOfSize:14];
  396. }
  397. messageLabel.numberOfLines = 0;
  398. messageLabel.textAlignment = NSTextAlignmentCenter;
  399. [messageLabel sizeToFit];
  400. [self.tableView reloadData];
  401. self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  402. self.tableView.backgroundView = messageLabel;
  403. } else {
  404. [self.tableView setBackgroundView:nil];
  405. self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
  406. }
  407. }
  408. - (void)setUINavigationBarDefault
  409. {
  410. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  411. UIBarButtonItem *buttonMore, *buttonNotification;
  412. // =
  413. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_more] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  414. buttonMore.enabled = true;
  415. // <
  416. self.navigationController.navigationBar.hidden = NO;
  417. // Notification
  418. if ([app.listOfNotifications count] > 0) {
  419. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_notification] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  420. buttonNotification.tintColor = COLOR_NAVIGATIONBAR_TEXT;
  421. buttonNotification.enabled = true;
  422. }
  423. if (buttonNotification)
  424. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  425. else
  426. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  427. self.navigationItem.leftBarButtonItem = nil;
  428. // close Menu
  429. [app.reSelectMenu close];
  430. }
  431. - (void)setUINavigationBarSelected
  432. {
  433. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  434. UIImage *icon = [UIImage imageNamed:image_more];
  435. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  436. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  437. self.navigationItem.leftBarButtonItem = leftButton;
  438. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  439. }
  440. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  441. {
  442. // close the menus
  443. if (app.reMainMenu.isOpen)
  444. [app.reMainMenu close];
  445. if (app.reSelectMenu.isOpen)
  446. [app.reSelectMenu close];
  447. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  448. }];
  449. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  450. }
  451. - (void)cancelSelect
  452. {
  453. [self tableViewSelect:NO];
  454. }
  455. #pragma --------------------------------------------------------------------------------------------
  456. #pragma mark ===== Document Picker =====
  457. #pragma --------------------------------------------------------------------------------------------
  458. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  459. {
  460. NSLog(@"Cancelled");
  461. }
  462. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  463. {
  464. NSLog(@"Cancelled");
  465. }
  466. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  467. {
  468. documentPicker.delegate = self;
  469. [self presentViewController:documentPicker animated:YES completion:nil];
  470. }
  471. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  472. {
  473. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  474. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  475. __block NSError *error;
  476. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  477. NSString *fileName = [url lastPathComponent];
  478. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  479. NSData *data = [NSData dataWithContentsOfURL:newURL];
  480. if (data && error == nil) {
  481. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  482. // Upload File
  483. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  484. } else {
  485. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  486. }
  487. } else {
  488. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  489. }
  490. }];
  491. }
  492. }
  493. - (void)openImportDocumentPicker
  494. {
  495. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  496. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  497. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  498. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  499. documentProviderMenu.delegate = self;
  500. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  501. }
  502. #pragma --------------------------------------------------------------------------------------------
  503. #pragma mark ===== Assets Picker =====
  504. #pragma --------------------------------------------------------------------------------------------
  505. - (void)openAssetsPickerController
  506. {
  507. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  508. checkmark.tintColor = COLOR_BRAND;
  509. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  510. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  511. [CCAspect aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  512. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  513. dispatch_async(dispatch_get_main_queue(), ^{
  514. // init picker
  515. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  516. // set delegate
  517. picker.delegate = self;
  518. // to show selection order
  519. //picker.showsSelectionIndex = YES;
  520. // to present picker as a form sheet in iPad
  521. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  522. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  523. // present picker
  524. [self presentViewController:picker animated:YES completion:nil];
  525. });
  526. }];
  527. }
  528. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  529. {
  530. [picker dismissViewControllerAnimated:YES completion:^{
  531. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session];
  532. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  533. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  534. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  535. //navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  536. [self presentViewController:navigationController animated:YES completion:nil];
  537. }];
  538. }
  539. #pragma --------------------------------------------------------------------------------------------
  540. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  541. #pragma --------------------------------------------------------------------------------------------
  542. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  543. {
  544. // evitiamo il rimando della eventuale photo e/o video
  545. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount]) {
  546. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  547. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  548. }
  549. }
  550. #pragma --------------------------------------------------------------------------------------------
  551. #pragma mark ===== UnZipFile =====
  552. #pragma --------------------------------------------------------------------------------------------
  553. - (void)unZipFile:(NSString *)fileID
  554. {
  555. [_hudDeterminate visibleHudTitle:NSLocalizedString(@"_unzip_in_progress_", nil) mode:MBProgressHUDModeDeterminate color:nil];
  556. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  557. NSString *fileZip = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID];
  558. [SSZipArchive unzipFileAtPath:fileZip toDestination:[CCUtility getDirectoryLocal] overwrite:YES password:nil progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
  559. dispatch_async(dispatch_get_main_queue(), ^{
  560. float progress = (float) entryNumber / (float)total;
  561. [_hudDeterminate progress:progress];
  562. });
  563. } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
  564. dispatch_async(dispatch_get_main_queue(), ^{
  565. [_hudDeterminate hideHud];
  566. if (succeeded) [app messageNotification:@"_info_" description:@"_file_unpacked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  567. else [app messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error %ld", (long)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  568. });
  569. }];
  570. });
  571. }
  572. #pragma --------------------------------------------------------------------------------------------
  573. #pragma mark ===== Create New (OpenModel) =====
  574. #pragma --------------------------------------------------------------------------------------------
  575. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  576. {
  577. UIViewController *viewController;
  578. NSString *fileName, *uuid, *fileID, *serverUrl;
  579. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  580. [self.tableView deselectRowAtIndexPath:index animated:NO];
  581. if (isnew) {
  582. fileName = nil;
  583. uuid = [CCUtility getUUID];
  584. fileID = nil;
  585. serverUrl = _serverUrl;
  586. } else {
  587. fileName = _metadata.fileName;
  588. uuid = _metadata.uuid;
  589. fileID = _metadata.fileID;
  590. serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  591. }
  592. if ([tipo isEqualToString:@"cartadicredito"])
  593. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  594. if ([tipo isEqualToString:@"bancomat"])
  595. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  596. if ([tipo isEqualToString:@"contocorrente"])
  597. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  598. if ([tipo isEqualToString:@"accountweb"])
  599. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  600. if ([tipo isEqualToString:@"patenteguida"])
  601. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  602. if ([tipo isEqualToString:@"cartaidentita"])
  603. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  604. if ([tipo isEqualToString:@"passaporto"])
  605. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  606. if ([tipo isEqualToString:@"note"]) {
  607. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  608. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  609. [self presentViewController:navigationController animated:YES completion:nil];
  610. } else {
  611. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  612. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  613. [self presentViewController:navigationController animated:YES completion:nil];
  614. }
  615. }
  616. // New folder or new photo or video
  617. - (void)returnCreate:(NSInteger)type
  618. {
  619. switch (type) {
  620. /* PLAIN */
  621. case k_returnCreateFolderPlain: {
  622. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  623. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  624. alertView.tag = alertCreateFolder;
  625. [alertView show];
  626. }
  627. break;
  628. case k_returnCreateFotoVideoPlain: {
  629. _isPickerCriptate = false;
  630. [self openAssetsPickerController];
  631. }
  632. break;
  633. case k_returnCreateFilePlain: {
  634. _isPickerCriptate = false;
  635. [self openImportDocumentPicker];
  636. }
  637. break;
  638. /* ENCRYPTED */
  639. case k_returnCreateFolderEncrypted: {
  640. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  641. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  642. alertView.tag = alertCreateFolderCrypto;
  643. [alertView show];
  644. }
  645. break;
  646. case k_returnCreateFotoVideoEncrypted: {
  647. _isPickerCriptate = true;
  648. [self openAssetsPickerController];
  649. }
  650. break;
  651. case k_returnCreateFileEncrypted: {
  652. _isPickerCriptate = true;
  653. [self openImportDocumentPicker];
  654. }
  655. break;
  656. /* UTILITY */
  657. case k_returnNote:
  658. [self openModel:@"note" isNew:true];
  659. break;
  660. case k_returnAccountWeb:
  661. [self openModel:@"accountweb" isNew:true];
  662. break;
  663. /* BANK */
  664. case k_returnCartaDiCredito:
  665. [self openModel:@"cartadicredito" isNew:true];
  666. break;
  667. case k_returnBancomat:
  668. [self openModel:@"bancomat" isNew:true];
  669. break;
  670. case k_returnContoCorrente:
  671. [self openModel:@"contocorrente" isNew:true];
  672. break;
  673. /* DOCUMENT */
  674. case k_returnPatenteGuida:
  675. [self openModel:@"patenteguida" isNew:true];
  676. break;
  677. case k_returnCartaIdentita:
  678. [self openModel:@"cartaidentita" isNew:true];
  679. break;
  680. case k_returnPassaporto:
  681. [self openModel:@"passaporto" isNew:true];
  682. break;
  683. }
  684. }
  685. #pragma --------------------------------------------------------------------------------------------
  686. #pragma mark ===== Save selected File =====
  687. #pragma --------------------------------------------------------------------------------------------
  688. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  689. {
  690. if (error)
  691. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  692. else
  693. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  694. }
  695. - (void)saveSelectedFiles
  696. {
  697. NSLog(@"[LOG] Start download selected files ...");
  698. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  699. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  700. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  701. for (CCMetadata *metadata in metadatas) {
  702. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  703. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  704. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  705. }
  706. }
  707. [_hud hideHud];
  708. });
  709. [self tableViewSelect:NO];
  710. }
  711. #pragma --------------------------------------------------------------------------------------------
  712. #pragma mark ===== Change Password =====
  713. #pragma --------------------------------------------------------------------------------------------
  714. - (void) loginSuccess:(NSInteger)loginType
  715. {
  716. [self readFolderWithForced:YES];
  717. }
  718. - (void)changePasswordAccount
  719. {
  720. CCLogin *loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  721. loginVC.delegate = self;
  722. loginVC.loginType = loginModifyPasswordUser;
  723. [self presentViewController:loginVC animated:YES completion:nil];
  724. }
  725. #pragma mark -
  726. #pragma --------------------------------------------------------------------------------------------
  727. #pragma mark ===== Peek & Pop =====
  728. #pragma --------------------------------------------------------------------------------------------
  729. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  730. {
  731. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  732. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  733. if (metadata.thumbnailExists && !metadata.cryptated) {
  734. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  735. if (cell) {
  736. previewingContext.sourceRect = cell.frame;
  737. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  738. vc.delegate = self;
  739. vc.metadata = metadata;
  740. return vc;
  741. }
  742. }
  743. return nil;
  744. }
  745. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  746. {
  747. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  748. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  749. }
  750. #pragma mark -
  751. #pragma --------------------------------------------------------------------------------------------
  752. #pragma mark ==== Notification ====
  753. #pragma --------------------------------------------------------------------------------------------
  754. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  755. {
  756. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  757. NSString *old = @"", *new = @"";
  758. // Order by date
  759. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  760. OCNotifications *notification1 = obj1, *notification2 = obj2;
  761. return [notification2.date compare: notification1.date];
  762. }];
  763. // verify if listOfNotifications is changed
  764. for (OCNotifications *notification in listOfNotifications)
  765. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  766. for (OCNotifications *notification in appDelegate.listOfNotifications)
  767. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  768. if (![new isEqualToString:old]) {
  769. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  770. // reload Notification view
  771. [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationReloadData" object:nil];
  772. }
  773. // Update NavigationBar
  774. if (!_isSelectedMode)
  775. [self setUINavigationBarDefault];
  776. }
  777. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  778. {
  779. // Update NavigationBar
  780. if (!_isSelectedMode)
  781. [self setUINavigationBarDefault];
  782. }
  783. - (void)viewNotification
  784. {
  785. if ([app.listOfNotifications count] > 0) {
  786. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  787. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  788. [self presentViewController:notificationVC animated:YES completion:nil];
  789. }
  790. }
  791. #pragma --------------------------------------------------------------------------------------------
  792. #pragma mark ==== Request Server ====
  793. #pragma --------------------------------------------------------------------------------------------
  794. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  795. {
  796. [CCCoreData setUserProfileActiveAccount:metadataNet.account userProfile:userProfile];
  797. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  798. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  799. if (avatar)
  800. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  801. else
  802. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  803. }
  804. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  805. {
  806. app.capabilities = capabilities;
  807. }
  808. - (void)getFeaturesSupportedByServerSuccess:(BOOL)hasCapabilitiesSupport hasForbiddenCharactersSupport:(BOOL)hasForbiddenCharactersSupport hasShareSupport:(BOOL)hasShareSupport hasShareeSupport:(BOOL)hasShareeSupport
  809. {
  810. app.hasServerCapabilitiesSupport = hasCapabilitiesSupport;
  811. app.hasServerForbiddenCharactersSupport = hasForbiddenCharactersSupport;
  812. app.hasServerShareSupport = hasShareSupport;
  813. app.hasServerShareeSupport = hasShareeSupport;
  814. if (hasShareSupport || hasShareeSupport)
  815. [self requestSharedByServer];
  816. }
  817. - (void)getInfoServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  818. {
  819. if (errorCode == 401)
  820. [self changePasswordAccount];
  821. }
  822. - (void)requestServerInformation
  823. {
  824. // test
  825. if (app.activeAccount.length == 0)
  826. return;
  827. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  828. [app.sharesID removeAllObjects];
  829. app.hasServerForbiddenCharactersSupport = YES;
  830. app.hasServerShareSupport = YES;
  831. metadataNet.action = actionGetFeaturesSuppServer;
  832. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  833. metadataNet.action = actionGetCapabilities;
  834. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  835. metadataNet.action = actionGetNotificationServer;
  836. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  837. metadataNet.action = actionGetUserProfile;
  838. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  839. }
  840. #pragma --------------------------------------------------------------------------------------------
  841. #pragma mark ==== Download Thumbnail ====
  842. #pragma --------------------------------------------------------------------------------------------
  843. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  844. {
  845. __block CCCellMain *cell;
  846. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  847. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  848. cell = [self.tableView cellForRowAtIndexPath:indexPath];
  849. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadataNet.fileID];
  850. if (cell.fileImageView.image == nil) {
  851. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  852. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]];
  853. [app.icoImagesCache setObject:image forKey:metadataNet.fileID];
  854. });
  855. }
  856. }
  857. }
  858. - (void)downloadThumbnailFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  859. {
  860. NSLog(@"[LOG] Thumbnail Error %@ %@ (error %ld)", metadataNet.fileName , message, (long)errorCode);
  861. }
  862. - (void)downloadThumbnail:(CCMetadata *)metadata
  863. {
  864. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  865. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  866. metadataNet.action = actionDownloadThumbnail;
  867. metadataNet.fileID = metadata.fileID;
  868. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  869. metadataNet.fileNameLocal = metadata.fileID;
  870. metadataNet.fileNamePrint = metadata.fileNamePrint;
  871. metadataNet.options = @"m";
  872. metadataNet.priority = NSOperationQueuePriorityLow;
  873. metadataNet.selector = selectorDownloadThumbnail;
  874. metadataNet.serverUrl = serverUrl;
  875. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  876. }
  877. #pragma --------------------------------------------------------------------------------------------
  878. #pragma mark ==== Download ====
  879. #pragma --------------------------------------------------------------------------------------------
  880. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  881. {
  882. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  883. // File do not exists on server, remove in local
  884. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  885. [CCCoreData deleteFile:metadata serverUrl:serverUrl directoryUser:app.directoryUser activeAccount:app.activeAccount];
  886. }
  887. if ([selector isEqualToString:selectorLoadViewImage]) {
  888. dispatch_async(dispatch_get_main_queue(), ^{
  889. // Updating Detail
  890. if (app.activeDetail)
  891. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  892. // Updating Photos
  893. if (app.activePhotosCameraUpload)
  894. [app.activePhotosCameraUpload downloadFileFailure:errorCode];
  895. });
  896. } else {
  897. if (errorCode != kCFURLErrorCancelled)
  898. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  899. }
  900. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  901. }
  902. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  903. {
  904. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  905. if (metadata == nil) return;
  906. // reload
  907. if ([selector isEqualToString:selectorReload]) {
  908. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  909. }
  910. // Offline Directory
  911. if ([selector isEqualToString:selectorDownloadOffline]) {
  912. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  913. }
  914. // add Offline
  915. if ([selector isEqualToString:selectorAddOffline]) {
  916. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:YES activeAccount:app.activeAccount];
  917. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  918. }
  919. // encrypted file
  920. if ([selector isEqualToString:selectorEncryptFile]) {
  921. [self encryptedFile:metadata];
  922. }
  923. // decrypted file
  924. if ([selector isEqualToString:selectorDecryptFile]) {
  925. [self decryptedFile:metadata];
  926. }
  927. // open View File
  928. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  929. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  930. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  931. [self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  932. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  933. selector = selectorOpenIn;
  934. } else {
  935. _metadataSegue = metadata;
  936. _metadataSegue.sessionSelector = selector;
  937. if ([self shouldPerformSegue:serverUrl])
  938. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  939. }
  940. }
  941. // addLocal
  942. if ([selector isEqualToString:selectorAddLocal]) {
  943. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  944. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  945. [CCGraphics saveIcoWithFileID:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  946. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  947. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  948. }
  949. // Open with...
  950. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  951. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  952. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  953. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  954. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  955. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  956. _docController.delegate = self;
  957. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  958. }
  959. // Save to Photo Album
  960. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  961. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  962. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  963. // evitiamo il rimando photo
  964. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  965. UIImage *image = [UIImage imageWithContentsOfFile:file];
  966. if (image)
  967. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  968. else
  969. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  970. }
  971. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  972. // we avoid the cross-reference video
  973. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  974. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  975. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  976. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  977. } else {
  978. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  979. }
  980. }
  981. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  982. }
  983. // Copy File
  984. if ([selector isEqualToString:selectorLoadCopy]) {
  985. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  986. [self copyFileToPasteboard:metadata];
  987. }
  988. // download and view a template
  989. if ([selector isEqualToString:selectorLoadModelView]) {
  990. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  991. [self openModel:metadata.model isNew:false];
  992. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  993. }
  994. //download file plist
  995. if ([selector isEqualToString:selectorLoadPlist]) {
  996. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  997. long countSelectorLoadPlist = 0;
  998. for (NSOperation *operation in [app.netQueue operations]) {
  999. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1000. countSelectorLoadPlist++;
  1001. }
  1002. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount]]) {
  1003. dispatch_async(dispatch_get_main_queue(), ^{
  1004. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1005. });
  1006. }
  1007. }
  1008. //selectorLoadViewImage
  1009. if ([selector isEqualToString:selectorLoadViewImage]) {
  1010. dispatch_async(dispatch_get_main_queue(), ^{
  1011. // Detail
  1012. if (app.activeDetail)
  1013. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1014. // Photos
  1015. if (app.activePhotosCameraUpload)
  1016. [app.activePhotosCameraUpload downloadFileSuccess:metadata];
  1017. });
  1018. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1019. }
  1020. // if exists postselector call self with selectorPost
  1021. if ([selectorPost length] > 0)
  1022. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1023. }
  1024. - (void)downloadSelectedFiles
  1025. {
  1026. NSLog(@"[LOG] Start download selected files ...");
  1027. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1028. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1029. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1030. for (CCMetadata *metadata in selectedMetadatas) {
  1031. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file]) {
  1032. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1033. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorReload selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1034. }
  1035. }
  1036. [_hud hideHud];
  1037. });
  1038. [self tableViewSelect:NO];
  1039. }
  1040. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1041. {
  1042. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", app.activeAccount, directoryID] context:nil];
  1043. for (TableMetadata *recordMetadata in records) {
  1044. if ([CCUtility isCryptoPlistString:recordMetadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, recordMetadata.fileName]] == NO && [recordMetadata.session length] == 0) {
  1045. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1046. metadataNet.action = actionDownloadFile;
  1047. metadataNet.metadata = [CCCoreData insertEntityInMetadata:recordMetadata];
  1048. metadataNet.downloadData = NO;
  1049. metadataNet.downloadPlist = YES;
  1050. metadataNet.selector = selectorLoadPlist;
  1051. metadataNet.serverUrl = serverUrl;
  1052. metadataNet.session = k_download_session_foreground;
  1053. metadataNet.taskStatus = k_taskStatusResume;
  1054. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1055. }
  1056. }
  1057. }
  1058. #pragma --------------------------------------------------------------------------------------------
  1059. #pragma mark ===== Upload new Photos/Videos =====
  1060. #pragma --------------------------------------------------------------------------------------------
  1061. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1062. {
  1063. // Automatic upload
  1064. if([selector isEqualToString:selectorUploadAutomatic] || [selector isEqualToString:selectorUploadAutomaticAll])
  1065. [app loadTableAutomaticUploadForSelector:selector];
  1066. // Read File test do not exists
  1067. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1068. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  1069. // reUpload
  1070. if (metadata)
  1071. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1072. }
  1073. // Print error
  1074. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1075. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1076. }
  1077. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1078. }
  1079. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1080. {
  1081. // Automatic upload
  1082. if([selector isEqualToString:selectorUploadAutomatic] || [selector isEqualToString:selectorUploadAutomaticAll])
  1083. [app loadTableAutomaticUploadForSelector:selector];
  1084. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1085. [self readFolderWithForced:YES];
  1086. } else {
  1087. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1088. }
  1089. }
  1090. //
  1091. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1092. //
  1093. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1094. {
  1095. [_hud visibleHudTitle:nil mode:MBProgressHUDModeIndeterminate color:nil];
  1096. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1097. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1098. });
  1099. }
  1100. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1101. {
  1102. NSArray *assets = [arguments objectAtIndex:0];
  1103. NSString *serverUrl = [arguments objectAtIndex:1];
  1104. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1105. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1106. NSString * session = [arguments objectAtIndex:4];
  1107. // remove title (graphics)
  1108. [self setTitleBackgroundTableView:nil];
  1109. NSString *folderPhotos = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  1110. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1111. // Create if request the folder for Photos
  1112. if ((useSubFolder || [serverUrl isEqualToString:folderPhotos]) && [_serverUrl isEqualToString:serverUrl] == NO){
  1113. if(![app.activePhotosCameraUpload automaticCreateFolder:folderPhotos]) {
  1114. [_hud hideHud];
  1115. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  1116. return;
  1117. }
  1118. }
  1119. // Create if request the subfolders
  1120. if (useSubFolder) {
  1121. for (NSString *dateSubFolder in [CCUtility createNameSubFolder:assets]) {
  1122. if(![app.activePhotosCameraUpload automaticCreateFolder:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder]]) {
  1123. [_hud hideHud];
  1124. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  1125. return;
  1126. }
  1127. }
  1128. }
  1129. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1130. for (PHAsset *asset in assets) {
  1131. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1132. NSDate *assetDate = asset.creationDate;
  1133. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1134. // Create serverUrl if use sub folder
  1135. if (useSubFolder) {
  1136. [formatter setDateFormat:@"yyyy"];
  1137. NSString *yearString = [formatter stringFromDate:assetDate];
  1138. [formatter setDateFormat:@"MM"];
  1139. NSString *monthString = [formatter stringFromDate:assetDate];
  1140. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  1141. }
  1142. // Check if is in upload
  1143. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@) AND (session != NULL) AND (session != '')", app.activeAccount, directoryID, fileName];
  1144. NSArray *isRecordInSessions = [CCCoreData getTableMetadataWithPredicate:predicate context:nil];
  1145. if ([isRecordInSessions count] > 0) {
  1146. // next upload
  1147. continue;
  1148. } else {
  1149. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1150. metadataNet.action = actionReadFile;
  1151. metadataNet.identifier = asset.localIdentifier;
  1152. metadataNet.cryptated = cryptated;
  1153. metadataNet.fileName = fileName;
  1154. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1155. metadataNet.session = session;
  1156. metadataNet.selector = selectorReadFileUploadFile;
  1157. metadataNet.serverUrl = serverUrl;
  1158. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1159. }
  1160. }
  1161. [_hud hideHud];
  1162. }
  1163. #pragma --------------------------------------------------------------------------------------------
  1164. #pragma mark ==== Read File ====
  1165. #pragma --------------------------------------------------------------------------------------------
  1166. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1167. {
  1168. // UploadFile
  1169. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1170. // File not exists
  1171. if (errorCode == 404) {
  1172. metadataNet.action = actionUploadAsset;
  1173. metadataNet.errorCode = 0;
  1174. metadataNet.selector = selectorUploadFile;
  1175. metadataNet.selectorPost = nil;
  1176. metadataNet.taskStatus = k_taskStatusResume;
  1177. if ([metadataNet.session containsString:@"wwan"])
  1178. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1179. else
  1180. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1181. } else {
  1182. // error ho many retry befor notification and go to on next asses
  1183. if (metadataNet.errorRetry < 3) {
  1184. // Retry read file
  1185. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1186. } else {
  1187. // STOP check file, view message error
  1188. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1189. }
  1190. }
  1191. }
  1192. }
  1193. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(CCMetadata *)metadata
  1194. {
  1195. // ReadFile Folder for change rev
  1196. if ([metadataNet.selector isEqualToString:selectorReadFileFolder]) {
  1197. NSString *rev = [CCCoreData getDirectoryRevFromServerUrl:metadataNet.serverUrl activeAccount:app.activeAccount];
  1198. if (![metadata.rev isEqualToString:rev]) {
  1199. NSLog(@"Change etag, force reload folder %@", metadataNet.serverUrl);
  1200. [CCCoreData setDirectoryRev:metadata.rev serverUrl:metadataNet.serverUrl activeAccount:app.activeAccount];
  1201. [CCCoreData clearDateReadDirectory:metadataNet.serverUrl activeAccount:app.activeAccount];
  1202. CCMain *viewController = [app.listMainVC objectForKey:metadataNet.serverUrl];
  1203. if (viewController)
  1204. [viewController clearDateReadDataSource:nil];
  1205. }
  1206. }
  1207. // UploadFile
  1208. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1209. metadataNet.action = actionUploadAsset;
  1210. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1211. metadataNet.selector = selectorUploadFile;
  1212. metadataNet.selectorPost = nil;
  1213. metadataNet.taskStatus = k_taskStatusResume;
  1214. if ([metadataNet.session containsString:@"wwan"])
  1215. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1216. else
  1217. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1218. }
  1219. }
  1220. #pragma --------------------------------------------------------------------------------------------
  1221. #pragma mark ==== Read Folder ====
  1222. #pragma --------------------------------------------------------------------------------------------
  1223. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1224. {
  1225. // verify active user
  1226. TableAccount *record = [CCCoreData getActiveAccount];
  1227. [_hud hideHud];
  1228. [_refreshControl endRefreshing];
  1229. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1230. if (message && [record.account isEqualToString:metadataNet.account])
  1231. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1232. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1233. if (errorCode == 401)
  1234. [self changePasswordAccount];
  1235. }
  1236. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet permissions:(NSString *)permissions rev:(NSString *)rev metadatas:(NSArray *)metadatas
  1237. {
  1238. // verify active user
  1239. TableAccount *record = [CCCoreData getActiveAccount];
  1240. if (![record.account isEqualToString:metadataNet.account])
  1241. return;
  1242. // save father e update permission
  1243. _fatherPermission = permissions;
  1244. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", app.activeAccount, metadataNet.directoryID]];
  1245. NSArray *recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@)", app.activeAccount, metadataNet.directoryID] context:nil];
  1246. [CCCoreData setDateReadDirectoryID:metadataNet.directoryID activeAccount:app.activeAccount];
  1247. for (CCMetadata *metadata in metadatas) {
  1248. // type of file
  1249. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1250. // if crypto do not insert
  1251. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1252. // verify if the record encrypted has plist + crypto
  1253. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1254. BOOL isCryptoComplete = NO;
  1255. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1256. for (CCMetadata *completeMetadata in metadatas) {
  1257. if (completeMetadata.cryptated == NO) continue;
  1258. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1259. isCryptoComplete = YES;
  1260. break;
  1261. }
  1262. }
  1263. if (isCryptoComplete == NO) continue;
  1264. }
  1265. // verify if the record is in download/upload progress
  1266. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1267. CCMetadata *metadataDB = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@)", app.activeAccount, metadataNet.directoryID, metadata.fileName] context:nil];
  1268. // Upload
  1269. if (metadataDB.session && [metadataDB.session rangeOfString:@"upload"].location != NSNotFound) {
  1270. NSString *sessionID = metadataDB.sessionID;
  1271. // rename SessionID -> fileID
  1272. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]];
  1273. metadataDB.session = @"";
  1274. metadataDB.date = metadata.date;
  1275. metadataDB.fileID = metadata.fileID;
  1276. metadataDB.rev = metadata.fileID;
  1277. metadataDB.sessionError = @"";
  1278. metadataDB.sessionID = @"";
  1279. metadataDB.sessionTaskIdentifier = k_taskIdentifierDone;
  1280. metadataDB.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  1281. [CCCoreData updateMetadata:metadataDB predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, app.activeAccount] activeAccount:app.activeAccount activeUrl:app.activeUrl context:nil];
  1282. [CCCoreData addLocalFile:metadataDB activeAccount:app.activeAccount];
  1283. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:app.directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1284. continue;
  1285. }
  1286. // download in progress
  1287. if (metadataDB.session && [metadataDB.session rangeOfString:@"download"].location != NSNotFound) continue;
  1288. }
  1289. // end test, insert in CoreData
  1290. [CCCoreData addMetadata:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl context:nil];
  1291. }
  1292. // read plist
  1293. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1294. // File is changed ??
  1295. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1296. [[CCOfflineFileFolder sharedOfflineFileFolder] verifyChangeMedatas:metadatas serverUrl:metadataNet.serverUrl account:app.activeAccount offline:NO];
  1297. });
  1298. // this is the same directory
  1299. if ([metadataNet.serverUrl isEqualToString:_serverUrl]) {
  1300. // reload
  1301. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1302. // stoprefresh
  1303. [_refreshControl endRefreshing];
  1304. // Enable change user
  1305. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1306. [_hud hideHud];
  1307. }
  1308. }
  1309. - (void)readFolderWithForced:(BOOL)forced
  1310. {
  1311. [self setTitleBackgroundTableView:nil];
  1312. // init control
  1313. if (!_serverUrl || !app.activeAccount)
  1314. return;
  1315. // Search Mode
  1316. if (_isSearchMode) {
  1317. if (forced)
  1318. _reloadForcedFoderWhenSearchModeOff = YES;
  1319. [self updateSearchResultsForSearchController:self.searchController];
  1320. return;
  1321. }
  1322. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount];
  1323. if ([CCCoreData isDirectoryOutOfDate:k_dayForceReadFolder directoryID:directoryID activeAccount:app.activeAccount] || forced) {
  1324. if (_refreshControl.isRefreshing == NO)
  1325. [_hud visibleIndeterminateHud];
  1326. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1327. metadataNet.action = actionReadFolder;
  1328. metadataNet.date = [NSDate date];
  1329. metadataNet.directoryID = directoryID;
  1330. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1331. metadataNet.selector = selectorReadFolder;
  1332. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:directoryID activeAccount:app.activeAccount];
  1333. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1334. } else {
  1335. if ([_sectionDataSource.allRecordsDataSource count] == 0) [self setTitleBackgroundTableView:NSLocalizedString(@"_no_file_pull_down_",nil)];
  1336. else [self setTitleBackgroundTableView:nil];
  1337. }
  1338. }
  1339. #pragma mark -
  1340. #pragma --------------------------------------------------------------------------------------------
  1341. #pragma mark ===== Search =====
  1342. #pragma --------------------------------------------------------------------------------------------
  1343. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1344. {
  1345. _isSearchMode = YES;
  1346. [self deleteRefreshControl];
  1347. NSString *fileName = [CCUtility removeForbiddenCharacters:searchController.searchBar.text hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1348. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1349. _searchFileName = fileName;
  1350. [[CCActions sharedInstance] search:_serverUrl fileName:_searchFileName delegate:self];
  1351. }
  1352. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1353. [self reloadDatasource];
  1354. }
  1355. }
  1356. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1357. {
  1358. [self cancelSearchBar];
  1359. // Need reload folder
  1360. if (_reloadForcedFoderWhenSearchModeOff) {
  1361. _reloadForcedFoderWhenSearchModeOff = NO;
  1362. [self readFolderWithForced:YES];
  1363. }
  1364. }
  1365. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1366. {
  1367. if (message)
  1368. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1369. }
  1370. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1371. {
  1372. _searchResultMetadatas = [[NSArray alloc] initWithArray:metadatas];
  1373. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1374. }
  1375. - (void)cancelSearchBar
  1376. {
  1377. if (self.searchController.active) {
  1378. [self.searchController setActive:NO];
  1379. [self createRefreshControl];
  1380. _isSearchMode = NO;
  1381. _searchFileName = @"";
  1382. _dateReadDataSource = nil;
  1383. _searchResultMetadatas = [NSArray new];
  1384. [self reloadDatasource];
  1385. }
  1386. }
  1387. #pragma mark -
  1388. #pragma --------------------------------------------------------------------------------------------
  1389. #pragma mark ===== Delete File or Folder =====
  1390. #pragma --------------------------------------------------------------------------------------------
  1391. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1392. {
  1393. [self deleteFileOrFolderSuccess:metadataNet];
  1394. }
  1395. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1396. {
  1397. [_queueSelector removeObject:metadataNet.selector];
  1398. if ([_queueSelector count] == 0) {
  1399. [_hud hideHud];
  1400. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.metadata.fileID selector:metadataNet.selector];
  1401. // next
  1402. if ([_selectedMetadatas count] > 0) {
  1403. [_selectedMetadatas removeObjectAtIndex:0];
  1404. if ([_selectedMetadatas count] > 0)
  1405. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1406. }
  1407. }
  1408. }
  1409. - (void)deleteFileOrFolder:(CCMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1410. {
  1411. if (metadata.cryptated) {
  1412. [_queueSelector addObject:selectorDeleteCrypto];
  1413. [_queueSelector addObject:selectorDeletePlist];
  1414. } else {
  1415. [_queueSelector addObject:selectorDelete];
  1416. }
  1417. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1418. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1419. }
  1420. - (void)deleteSelectionFile
  1421. {
  1422. [_selectedMetadatas removeAllObjects];
  1423. [_queueSelector removeAllObjects];
  1424. _selectedMetadatas = [[NSMutableArray alloc] initWithArray: [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]]];
  1425. _numSelectedMetadatas = [_selectedMetadatas count];
  1426. if ([_selectedMetadatas count] > 0)
  1427. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1428. [self tableViewSelect:NO];
  1429. }
  1430. - (void)deleteFile
  1431. {
  1432. [_selectedMetadatas removeAllObjects];
  1433. [_queueSelector removeAllObjects];
  1434. _numSelectedMetadatas = 1;
  1435. [_selectedMetadatas addObject:_metadata];
  1436. if ([_selectedMetadatas count] > 0)
  1437. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1438. [self tableViewSelect:NO];
  1439. }
  1440. #pragma --------------------------------------------------------------------------------------------
  1441. #pragma mark ===== Rename / Move =====
  1442. #pragma --------------------------------------------------------------------------------------------
  1443. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1444. {
  1445. [self readFolderWithForced:YES];
  1446. }
  1447. - (void)renameFile:(CCMetadata *)metadata fileName:(NSString *)fileName
  1448. {
  1449. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1450. }
  1451. - (void)renameNote:(CCMetadata *)metadata fileName:(NSString *)fileName
  1452. {
  1453. CCTemplates *templates = [[CCTemplates alloc] init];
  1454. CCCrypto *crypto = [[CCCrypto alloc] init];
  1455. NSMutableDictionary *field = [crypto getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1456. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1457. if (fileNameModel) {
  1458. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1459. metadataNet.action = actionUploadTemplate;
  1460. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1461. metadataNet.fileNamePrint = fileName;
  1462. metadataNet.rev = metadata.rev;
  1463. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1464. metadataNet.session = k_upload_session_foreground;
  1465. metadataNet.taskStatus = k_taskStatusResume;
  1466. if ([CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount])
  1467. metadataNet.selectorPost = selectorAddOffline;
  1468. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1469. }
  1470. }
  1471. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1472. {
  1473. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1474. [_hud hideHud];
  1475. if (message)
  1476. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1477. [_selectedMetadatas removeAllObjects];
  1478. [_queueSelector removeAllObjects];
  1479. }
  1480. }
  1481. - (void)moveSuccess:(CCMetadataNet *)metadataNet revTo:(NSString *)revTo
  1482. {
  1483. [_queueSelector removeObject:metadataNet.selector];
  1484. if ([_queueSelector count] == 0) {
  1485. [_hud hideHud];
  1486. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1487. NSString *directoryID = metadataNet.directoryID;
  1488. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1489. NSString *serverUrlTo = [CCCoreData getServerUrlFromDirectoryID:directoryIDTo activeAccount:app.activeAccount];
  1490. // FILE -> Metadata
  1491. if (metadataNet.directory == NO) {
  1492. // move metadata
  1493. [CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1494. }
  1495. // DIRECTORY -> Directory - CCMetadata
  1496. if (metadataNet.directory == YES) {
  1497. // delete all dir / subdir
  1498. NSArray *directoryIDs = [CCCoreData deleteDirectoryAndSubDirectory:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addServerUrl:fileName] activeAccount:app.activeAccount];
  1499. // delete all metadata and local file in dir / subdir
  1500. for (NSString *directoryIDDelete in directoryIDs)
  1501. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(directoryID == %@)AND (account == %@)",directoryIDDelete, app.activeAccount]];
  1502. // move metadata
  1503. [CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1504. // Add new directory
  1505. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1506. [CCCoreData addDirectory:newDirectory date:[NSDate date] permissions:nil activeAccount:app.activeAccount];
  1507. // Check Offline
  1508. if ([CCCoreData isOfflineDirectoryServerUrl:serverUrlTo activeAccount:app.activeAccount])
  1509. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1510. }
  1511. // reload Datasource
  1512. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced])
  1513. [self readFolderWithForced:YES];
  1514. else
  1515. [self reloadDatasource];
  1516. // Next file
  1517. [_selectedMetadatas removeObjectAtIndex:0];
  1518. [self moveFileOrFolder:metadataNet.serverUrlTo];
  1519. }
  1520. }
  1521. - (void)moveFileOrFolder:(NSString *)serverUrlTo
  1522. {
  1523. if ([_selectedMetadatas count] > 0) {
  1524. CCMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  1525. // Plain
  1526. if (metadata.cryptated == NO) {
  1527. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1528. metadataNet.action = actionMoveFileOrFolder;
  1529. metadataNet.directory = metadata.directory;
  1530. metadataNet.fileID = metadata.fileID;
  1531. metadataNet.directoryID = metadata.directoryID;
  1532. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1533. metadataNet.fileName = metadata.fileName;
  1534. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1535. metadataNet.fileNameTo = metadata.fileName;
  1536. metadataNet.rev = metadata.rev;
  1537. metadataNet.selector = selectorMove;
  1538. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1539. metadataNet.serverUrlTo = serverUrlTo;
  1540. [_queueSelector addObject:metadataNet.selector];
  1541. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1542. }
  1543. // cyptated
  1544. if (metadata.cryptated == YES) {
  1545. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1546. metadataNet.action = actionMoveFileOrFolder;
  1547. metadataNet.directory = metadata.directory;
  1548. metadataNet.fileID = metadata.fileID;
  1549. metadataNet.directoryID = metadata.directoryID;
  1550. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1551. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1552. metadataNet.rev = metadata.rev;
  1553. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1554. metadataNet.serverUrlTo = serverUrlTo;
  1555. // data
  1556. metadataNet.fileName = metadata.fileNameData;
  1557. metadataNet.fileNameTo = metadata.fileNameData;
  1558. metadataNet.selector = selectorMoveCrypto;
  1559. [_queueSelector addObject:metadataNet.selector];
  1560. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1561. // plist
  1562. metadataNet.fileName = metadata.fileName;
  1563. metadataNet.fileNameTo = metadata.fileName;
  1564. metadataNet.selector = selectorMovePlist;
  1565. [_queueSelector addObject:metadataNet.selector];
  1566. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1567. }
  1568. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), _numSelectedMetadatas - [_selectedMetadatas count] + 1, _numSelectedMetadatas] mode:MBProgressHUDModeIndeterminate color:nil];
  1569. }
  1570. }
  1571. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title selectedMetadatas:(NSArray *)selectedMetadatas
  1572. {
  1573. // Test
  1574. if ([_serverUrl isEqualToString:serverUrlTo]) {
  1575. [self tableViewSelect:NO];
  1576. return;
  1577. }
  1578. [_selectedMetadatas removeAllObjects];
  1579. [_queueSelector removeAllObjects];
  1580. _selectedMetadatas = [[NSMutableArray alloc] initWithArray:selectedMetadatas];
  1581. _numSelectedMetadatas = [_selectedMetadatas count];
  1582. [self moveFileOrFolder:serverUrlTo];
  1583. [self tableViewSelect:NO];
  1584. }
  1585. - (void)moveOpenWindow:(NSArray *)indexPaths
  1586. {
  1587. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1588. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1589. viewController.delegate = self;
  1590. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1591. viewController.selectedMetadatas = [self getMetadatasFromSelectedRows:indexPaths];
  1592. viewController.tintColor = COLOR_NAVIGATIONBAR_TEXT;
  1593. viewController.barTintColor = COLOR_NAVIGATIONBAR;
  1594. viewController.tintColorTitle = COLOR_NAVIGATIONBAR_TEXT;
  1595. viewController.networkingOperationQueue = app.netQueue;
  1596. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1597. [self presentViewController:navigationController animated:YES completion:nil];
  1598. }
  1599. #pragma --------------------------------------------------------------------------------------------
  1600. #pragma mark ===== Create folder =====
  1601. #pragma --------------------------------------------------------------------------------------------
  1602. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1603. {
  1604. [_hud hideHud];
  1605. if (message)
  1606. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1607. }
  1608. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1609. {
  1610. [_hud hideHud];
  1611. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1612. [CCCoreData addDirectory:newDirectory date:[NSDate date] permissions:nil activeAccount:app.activeAccount];
  1613. // Check Offline
  1614. if ([CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount])
  1615. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1616. // Load Folder or the Datasource
  1617. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1618. [self readFolderWithForced:YES];
  1619. } else {
  1620. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1621. }
  1622. }
  1623. - (void)createFolder:(NSString *)fileNameFolder folderCameraUpload:(BOOL)folderCameraUpload
  1624. {
  1625. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1626. fileNameFolder = [CCUtility removeForbiddenCharacters:fileNameFolder hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1627. if (![fileNameFolder length]) return;
  1628. if (folderCameraUpload) metadataNet.serverUrl = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  1629. else metadataNet.serverUrl = _serverUrl;
  1630. metadataNet.action = actionCreateFolder;
  1631. if (folderCameraUpload)
  1632. metadataNet.options = @"folderCameraUpload";
  1633. metadataNet.fileName = fileNameFolder;
  1634. metadataNet.selector = selectorCreateFolder;
  1635. metadataNet.selectorPost = selectorReadFolderForced;
  1636. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1637. if (!folderCameraUpload)
  1638. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1639. }
  1640. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1641. {
  1642. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1643. CCCrypto *crypto = [[CCCrypto alloc] init];
  1644. NSString *fileNamePlist;
  1645. fileNameFolder = [CCUtility removeForbiddenCharacters:fileNameFolder hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1646. if (![fileNameFolder length]) return;
  1647. NSString *title = [AESCrypt encrypt:fileNameFolder password:[crypto getKeyPasscode:[CCUtility getUUID]]];
  1648. fileNamePlist = [crypto createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1649. [crypto createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1650. // Create folder
  1651. metadataNet.action = actionCreateFolder;
  1652. metadataNet.fileName = fileNamePlist;
  1653. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1654. metadataNet.selector = selectorCreateFolder;
  1655. metadataNet.serverUrl = _serverUrl;
  1656. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1657. // upload plist file
  1658. metadataNet.action = actionUploadOnlyPlist;
  1659. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1660. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1661. metadataNet.selectorPost = selectorReadFolderForced;
  1662. metadataNet.serverUrl = _serverUrl;
  1663. metadataNet.session = k_upload_session_foreground;
  1664. metadataNet.taskStatus = k_taskStatusResume;
  1665. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1666. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1667. }
  1668. - (void)createFolderCameraUpload
  1669. {
  1670. [self createFolder:[CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount] folderCameraUpload:YES];
  1671. }
  1672. #pragma --------------------------------------------------------------------------------------------
  1673. #pragma mark ===== Encrypted / Decrypted Folder =====
  1674. #pragma --------------------------------------------------------------------------------------------
  1675. - (void)encyptedDecryptedFolder
  1676. {
  1677. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1678. if (_metadata.cryptated) {
  1679. // DECRYPTED
  1680. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1681. //-------------------------- RENAME -------------------------------------------//
  1682. metadataNet.action = actionMoveFileOrFolder;
  1683. metadataNet.fileID = _metadata.fileID;
  1684. metadataNet.fileName = _metadata.fileNameData;
  1685. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1686. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1687. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1688. metadataNet.selector = selectorRename;
  1689. metadataNet.serverUrl = serverUrl;
  1690. metadataNet.serverUrlTo = serverUrl;
  1691. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1692. //-------------------------- DELETE -------------------------------------------//
  1693. metadataNet.action = actionDeleteFileDirectory;
  1694. metadataNet.fileID = _metadata.fileID;
  1695. metadataNet.fileName = _metadata.fileName;
  1696. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1697. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1698. metadataNet.selector = selectorDeletePlist;
  1699. metadataNet.selectorPost = selectorReadFolderForced;
  1700. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1701. } else {
  1702. // ENCRYPTED
  1703. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1704. CCCrypto *crypto = [[CCCrypto alloc] init];
  1705. // Create File Plist
  1706. NSString *fileNameCrypto = [crypto createFileDirectoryPlist:_metadata];
  1707. //-------------------------- RENAME -------------------------------------------//
  1708. metadataNet.action = actionMoveFileOrFolder;
  1709. metadataNet.fileID = _metadata.fileID;
  1710. metadataNet.fileName = _metadata.fileName;
  1711. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1712. metadataNet.fileNameTo = fileNameCrypto;
  1713. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1714. metadataNet.selector = selectorRename;
  1715. metadataNet.serverUrl = serverUrl;
  1716. metadataNet.serverUrlTo = serverUrl;
  1717. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1718. //-------------------------- UPLOAD -------------------------------------------//
  1719. metadataNet.action = actionUploadOnlyPlist;
  1720. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1721. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1722. metadataNet.selectorPost = selectorReadFolderForced;
  1723. metadataNet.serverUrl = serverUrl;
  1724. metadataNet.session = k_upload_session_foreground;
  1725. metadataNet.taskStatus = k_taskStatusResume;
  1726. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1727. }
  1728. }
  1729. #pragma --------------------------------------------------------------------------------------------
  1730. #pragma mark ===== Encrypted/Decrypted File =====
  1731. #pragma --------------------------------------------------------------------------------------------
  1732. - (void)encryptedSelectedFiles
  1733. {
  1734. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1735. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1736. for (CCMetadata *metadata in selectedMetadatas) {
  1737. if (metadata.cryptated == NO && metadata.directory == NO)
  1738. [metadatas addObject:metadata];
  1739. }
  1740. if ([metadatas count] > 0) {
  1741. NSLog(@"[LOG] Start encrypted selected files ...");
  1742. for (CCMetadata* metadata in metadatas) {
  1743. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1744. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1745. }
  1746. }
  1747. [self tableViewSelect:NO];
  1748. }
  1749. - (void)decryptedSelectedFiles
  1750. {
  1751. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1752. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1753. for (CCMetadata *metadata in selectedMetadatas) {
  1754. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1755. [metadatas addObject:metadata];
  1756. }
  1757. if ([metadatas count] > 0) {
  1758. NSLog(@"[LOG] Start decrypted selected files ...");
  1759. for (CCMetadata* metadata in metadatas) {
  1760. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1761. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1762. }
  1763. }
  1764. [self tableViewSelect:NO];
  1765. }
  1766. - (void)cmdEncryptedDecryptedFile
  1767. {
  1768. NSString *selector;
  1769. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1770. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1771. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1772. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1773. }
  1774. - (void)encryptedFile:(CCMetadata *)metadata
  1775. {
  1776. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1777. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1778. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1779. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1780. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1781. dispatch_async(dispatch_get_main_queue(), ^{
  1782. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1783. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1784. });
  1785. } else {
  1786. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1787. }
  1788. }
  1789. - (void)decryptedFile:(CCMetadata *)metadata
  1790. {
  1791. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1792. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1793. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1794. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1795. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1796. dispatch_async(dispatch_get_main_queue(), ^{
  1797. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1798. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1799. });
  1800. } else {
  1801. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1802. }
  1803. }
  1804. #pragma --------------------------------------------------------------------------------------------
  1805. #pragma mark ===== Progress & Task Button =====
  1806. #pragma --------------------------------------------------------------------------------------------
  1807. - (void)progressTask:(NSString *)fileID serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated progress:(float)progress;
  1808. {
  1809. // Check
  1810. if (!fileID)
  1811. return;
  1812. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1813. if (![serverUrl isEqualToString:_serverUrl])
  1814. return;
  1815. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1816. if (indexPath) {
  1817. CCControlCenterCell *cell = (CCControlCenterCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1818. if (cryptated) cell.progressView.progressTintColor = COLOR_CRYPTOCLOUD;
  1819. else cell.progressView.progressTintColor = COLOR_TEXT_ANTHRACITE;
  1820. cell.progressView.hidden = NO;
  1821. [cell.progressView setProgress:progress];
  1822. }
  1823. }
  1824. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1825. {
  1826. UITouch * touch = [[event allTouches] anyObject];
  1827. CGPoint location = [touch locationInView:self.tableView];
  1828. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1829. if (indexPath) {
  1830. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1831. if (metadata)
  1832. [self reloadTaskButton:metadata];
  1833. }
  1834. }
  1835. - (void)reloadTaskButton:(CCMetadata *)metadata
  1836. {
  1837. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1838. __block NSURLSessionTask *findTask;
  1839. // DOWNLOAD
  1840. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1841. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1842. for (NSURLSessionUploadTask *task in downloadTasks)
  1843. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1844. findTask = task;
  1845. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  1846. [task cancel];
  1847. }
  1848. if (!findTask) {
  1849. dispatch_async(dispatch_get_main_queue(), ^{
  1850. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  1851. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1852. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1853. });
  1854. }
  1855. }];
  1856. }
  1857. // UPLOAD
  1858. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1859. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1860. for (NSURLSessionUploadTask *task in uploadTasks)
  1861. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1862. findTask = task;
  1863. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  1864. [task cancel];
  1865. }
  1866. if (!findTask) {
  1867. dispatch_async(dispatch_get_main_queue(), ^{
  1868. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  1869. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1870. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1871. });
  1872. }
  1873. }];
  1874. }
  1875. }
  1876. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1877. {
  1878. UITouch * touch = [[event allTouches] anyObject];
  1879. CGPoint location = [touch locationInView:self.tableView];
  1880. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1881. if (indexPath) {
  1882. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1883. if (metadata)
  1884. [self cancelTaskButton:metadata reloadTable:YES];
  1885. }
  1886. }
  1887. - (void)cancelTaskButton:(CCMetadata *)metadata reloadTable:(BOOL)reloadTable
  1888. {
  1889. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1890. __block NSURLSessionTask *findTask;
  1891. // DOWNLOAD
  1892. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1893. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1894. for (NSURLSessionTask *task in downloadTasks)
  1895. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1896. findTask = task;
  1897. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  1898. [task cancel];
  1899. }
  1900. if (!findTask) {
  1901. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  1902. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1903. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1904. }
  1905. }];
  1906. }
  1907. // UPLOAD
  1908. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1909. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1910. for (NSURLSessionUploadTask *task in uploadTasks)
  1911. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1912. findTask = task;
  1913. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  1914. [task cancel];
  1915. }
  1916. if (!findTask) {
  1917. dispatch_async(dispatch_get_main_queue(), ^{
  1918. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  1919. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1920. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1921. });
  1922. }
  1923. }];
  1924. }
  1925. }
  1926. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1927. {
  1928. UITouch * touch = [[event allTouches] anyObject];
  1929. CGPoint location = [touch locationInView:self.tableView];
  1930. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1931. if (indexPath) {
  1932. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1933. if (metadata)
  1934. [self stopTaskButton:metadata];
  1935. }
  1936. }
  1937. - (void)stopTaskButton:(CCMetadata *)metadata
  1938. {
  1939. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1940. __block NSURLSessionTask *findTask;
  1941. // UPLOAD
  1942. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1943. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1944. for (NSURLSessionUploadTask *task in uploadTasks)
  1945. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1946. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  1947. findTask = task;
  1948. [task cancel];
  1949. }
  1950. if (!findTask) {
  1951. dispatch_async(dispatch_get_main_queue(), ^{
  1952. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  1953. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1954. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1955. });
  1956. }
  1957. }];
  1958. }
  1959. }
  1960. #pragma --------------------------------------------------------------------------------------------
  1961. #pragma mark ===== Shared =====
  1962. #pragma --------------------------------------------------------------------------------------------
  1963. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1964. {
  1965. [_hud hideHud];
  1966. // change account ?
  1967. TableAccount *record = [CCCoreData getActiveAccount];
  1968. if([record.account isEqualToString:metadataNet.account] == NO)
  1969. return;
  1970. [CCCoreData updateShare:items sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup activeAccount:app.activeAccount activeUrl:app.activeUrl];
  1971. if (openWindow) {
  1972. if (_shareOC) {
  1973. [_shareOC reloadData];
  1974. } else {
  1975. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  1976. // Apriamo la view
  1977. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1978. _shareOC.delegate = self;
  1979. _shareOC.metadata = metadata;
  1980. _shareOC.serverUrl = metadataNet.serverUrl;
  1981. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  1982. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  1983. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1984. [self presentViewController:_shareOC animated:YES completion:nil];
  1985. }
  1986. }
  1987. [self tableViewReload];
  1988. }
  1989. - (void)requestSharedByServer
  1990. {
  1991. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1992. metadataNet.action = actionReadShareServer;
  1993. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1994. }
  1995. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1996. {
  1997. [_hud hideHud];
  1998. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1999. if (_shareOC)
  2000. [_shareOC reloadData];
  2001. [self tableViewReload];
  2002. if (errorCode == 401)
  2003. [self changePasswordAccount];
  2004. }
  2005. - (void)share:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2006. {
  2007. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2008. metadataNet.action = actionShare;
  2009. metadataNet.fileID = metadata.fileID;
  2010. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2011. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2012. metadataNet.password = password;
  2013. metadataNet.selector = selectorShare;
  2014. metadataNet.serverUrl = serverUrl;
  2015. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2016. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2017. }
  2018. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2019. {
  2020. [_hud hideHud];
  2021. // rimuoviamo la condivisione da db
  2022. [CCCoreData unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup activeAccount:app.activeAccount];
  2023. if (_shareOC)
  2024. [_shareOC reloadData];
  2025. [self tableViewReload];
  2026. }
  2027. - (void)unShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl
  2028. {
  2029. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2030. metadataNet.action = actionUnShare;
  2031. metadataNet.fileID = metadata.fileID;
  2032. metadataNet.fileName = metadata.fileName;
  2033. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2034. metadataNet.selector = selectorUnshare;
  2035. metadataNet.serverUrl = serverUrl;
  2036. metadataNet.share = share;
  2037. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2038. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2039. }
  2040. - (void)updateShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2041. {
  2042. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2043. metadataNet.action = actionUpdateShare;
  2044. metadataNet.fileID = metadata.fileID;
  2045. metadataNet.expirationTime = expirationTime;
  2046. metadataNet.password = password;
  2047. metadataNet.selector = selectorUpdateShare;
  2048. metadataNet.serverUrl = serverUrl;
  2049. metadataNet.share = share;
  2050. metadataNet.sharePermission = permission;
  2051. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2052. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2053. }
  2054. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2055. {
  2056. [_hud hideHud];
  2057. if (_shareOC)
  2058. [_shareOC reloadUserAndGroup:items];
  2059. }
  2060. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2061. {
  2062. [_hud hideHud];
  2063. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2064. }
  2065. - (void)getUserAndGroup:(NSString *)find
  2066. {
  2067. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2068. metadataNet.action = actionGetUserAndGroup;
  2069. metadataNet.options = find;
  2070. metadataNet.selector = selectorGetUserAndGroup;
  2071. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2072. [_hud visibleIndeterminateHud];
  2073. }
  2074. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(CCMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2075. {
  2076. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2077. metadataNet.action = actionShareWith;
  2078. metadataNet.fileID = metadata.fileID;
  2079. metadataNet.directoryID = directoryID;
  2080. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2081. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2082. metadataNet.serverUrl = serverUrl;
  2083. metadataNet.selector = selectorShare;
  2084. metadataNet.share = user;
  2085. metadataNet.shareeType = shareeType;
  2086. metadataNet.sharePermission = permission;
  2087. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2088. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2089. }
  2090. - (void)openWindowShare:(CCMetadata *)metadata
  2091. {
  2092. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2093. metadataNet.action = actionReadShareServer;
  2094. metadataNet.fileID = metadata.fileID;
  2095. metadataNet.fileName = metadata.fileName;
  2096. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2097. metadataNet.selector = selectorOpenWindowShare;
  2098. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2099. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2100. [_hud visibleIndeterminateHud];
  2101. }
  2102. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2103. {
  2104. CGPoint location = [tapGesture locationInView:self.tableView];
  2105. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2106. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2107. if (metadata)
  2108. [self openWindowShare:metadata];
  2109. }
  2110. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2111. {
  2112. CGPoint location = [tapGesture locationInView:self.tableView];
  2113. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2114. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2115. if (metadata) {
  2116. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2117. vc.metadata = metadata;
  2118. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2119. [self presentViewController:vc animated:YES completion:nil];
  2120. }
  2121. }
  2122. #pragma --------------------------------------------------------------------------------------------
  2123. #pragma mark ===== Offline =====
  2124. #pragma --------------------------------------------------------------------------------------------
  2125. - (void)addOffline:(CCMetadata *)metadata
  2126. {
  2127. if (metadata.errorPasscode || !metadata.uuid) return;
  2128. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2129. if ([metadata.type isEqualToString: k_metadataType_file])
  2130. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddOffline selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2131. if ([metadata.type isEqualToString: k_metadataType_template])
  2132. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:YES activeAccount:app.activeAccount];
  2133. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2134. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2135. }
  2136. - (void)removeOffline:(CCMetadata *)metadata
  2137. {
  2138. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:NO activeAccount:app.activeAccount];
  2139. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2140. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2141. }
  2142. #pragma --------------------------------------------------------------------------------------------
  2143. #pragma mark ===== Local =====
  2144. #pragma --------------------------------------------------------------------------------------------
  2145. - (void)addLocal:(CCMetadata *)metadata
  2146. {
  2147. if (metadata.errorPasscode || !metadata.uuid) return;
  2148. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2149. if ([metadata.type isEqualToString: k_metadataType_file])
  2150. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2151. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2152. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2153. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  2154. }
  2155. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2156. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2157. }
  2158. #pragma --------------------------------------------------------------------------------------------
  2159. #pragma mark ===== Reload =====
  2160. #pragma --------------------------------------------------------------------------------------------
  2161. - (void)reloadFile:(CCMetadata *)metadata
  2162. {
  2163. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2164. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorReload selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2165. }
  2166. #pragma --------------------------------------------------------------------------------------------
  2167. #pragma mark ===== Open in... =====
  2168. #pragma --------------------------------------------------------------------------------------------
  2169. - (void)openIn:(CCMetadata *)metadata
  2170. {
  2171. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2172. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2173. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2174. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2175. }
  2176. #pragma --------------------------------------------------------------------------------------------
  2177. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2178. #pragma --------------------------------------------------------------------------------------------
  2179. - (void)orderTable:(NSString *)order
  2180. {
  2181. // Clear data-read of DataSource
  2182. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2183. [CCUtility setOrderSettings:order];
  2184. // refresh
  2185. [self reloadDatasource];
  2186. // new menu
  2187. [self createReMainMenu];
  2188. }
  2189. - (void)ascendingTable:(BOOL)ascending
  2190. {
  2191. // Clear data-read of DataSource
  2192. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2193. [CCUtility setAscendingSettings:ascending];
  2194. // refresh
  2195. [self reloadDatasource];
  2196. // new menu
  2197. [self createReMainMenu];
  2198. }
  2199. - (void)directoryOnTop:(BOOL)directoryOnTop
  2200. {
  2201. // Clear data-read of DataSource
  2202. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2203. [CCUtility setDirectoryOnTop:directoryOnTop];
  2204. // refresh
  2205. [self reloadDatasource];
  2206. // new menu
  2207. [self createReMainMenu];
  2208. }
  2209. - (void)tableGroupBy:(NSString *)groupBy
  2210. {
  2211. // Clear data-read of DataSource
  2212. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2213. [CCUtility setGroupBySettings:groupBy];
  2214. // refresh
  2215. [self reloadDatasource];
  2216. // new menu
  2217. [self createReMainMenu];
  2218. }
  2219. #pragma --------------------------------------------------------------------------------------------
  2220. #pragma mark ==== Menu change User ====
  2221. #pragma --------------------------------------------------------------------------------------------
  2222. - (void)menuChangeUser
  2223. {
  2224. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2225. return;
  2226. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [CCCoreData countTableAutomaticUploadForAccount:app.activeAccount selector:nil] > 0) {
  2227. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  2228. return;
  2229. }
  2230. NSArray *listTableAccount = [CCCoreData getAllTableAccount];
  2231. NSMutableArray *menuArray = [[NSMutableArray alloc] init];
  2232. for (TableAccount *record in listTableAccount) {
  2233. if ([record.account isEqualToString:app.activeAccount]) continue;
  2234. CCMenuItem *item = [[CCMenuItem alloc] init];
  2235. item.title = [record.account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2236. item.argument = record.account;
  2237. item.image = [UIImage imageNamed:image_Nextcloud];
  2238. item.target = self;
  2239. item.action = @selector(changeDefaultAccount:);
  2240. [menuArray addObject:item];
  2241. }
  2242. if ([menuArray count] == 0)
  2243. return;
  2244. OptionalConfiguration options;
  2245. Color textColor, backgroundColor;
  2246. textColor.R = 0;
  2247. textColor.G = 0;
  2248. textColor.B = 0;
  2249. backgroundColor.R = 1;
  2250. backgroundColor.G = 1;
  2251. backgroundColor.B = 1;
  2252. NSInteger originY = 60;
  2253. options.arrowSize = 9;
  2254. options.marginXSpacing = 7;
  2255. options.marginYSpacing = 10;
  2256. options.intervalSpacing = 20;
  2257. options.menuCornerRadius = 6.5;
  2258. options.maskToBackground = NO;
  2259. options.shadowOfMenu = YES;
  2260. options.hasSeperatorLine = YES;
  2261. options.seperatorLineHasInsets = YES;
  2262. options.textColor = textColor;
  2263. options.menuBackgroundColor = backgroundColor;
  2264. CGRect rect = self.view.frame;
  2265. rect.origin.y = rect.origin.y + originY;
  2266. rect.size.height = rect.size.height - originY;
  2267. [CCMenu setTitleFont:[UIFont systemFontOfSize:12.0]];
  2268. [CCMenu showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2269. }
  2270. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2271. {
  2272. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2273. // STOP, erase all in queue networking
  2274. [app cancelAllOperations];
  2275. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2276. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2277. TableAccount *tableAccount = [CCCoreData setActiveAccount:[sender argument]];
  2278. if (tableAccount)
  2279. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2280. // go to home sweet home
  2281. [[NSNotificationCenter defaultCenter] postNotificationName:@"initializeMain" object:nil];
  2282. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2283. });
  2284. }
  2285. #pragma --------------------------------------------------------------------------------------------
  2286. #pragma mark ==== ReMenu ====
  2287. #pragma --------------------------------------------------------------------------------------------
  2288. - (void)createReMenuBackgroundView:(REMenu *)menu
  2289. {
  2290. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2291. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2292. [UIView animateWithDuration:0.2 animations:^{
  2293. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2294. if (height < self.tabBarController.tabBar.frame.size.height)
  2295. height = self.tabBarController.tabBar.frame.size.height;
  2296. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2297. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2298. }];
  2299. }
  2300. - (void)createReMainMenu
  2301. {
  2302. NSString *ordinamento;
  2303. NSString *groupBy = _directoryGroupBy;
  2304. __block NSString *nuovoOrdinamento;
  2305. NSString *titoloNuovo, *titoloAttuale;
  2306. BOOL ascendente;
  2307. __block BOOL nuovoAscendente;
  2308. UIImage *image;
  2309. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2310. if (app.selezionaItem == nil) app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)
  2311. subtitle:@""
  2312. image:[UIImage imageNamed:image_seleziona]
  2313. highlightedImage:nil
  2314. action:^(REMenuItem *item) {
  2315. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2316. [self tableViewSelect:YES];
  2317. }
  2318. }];
  2319. else app.selezionaItem = [app.selezionaItem initWithTitle:NSLocalizedString(@"_select_", nil)
  2320. subtitle:@""
  2321. image:[UIImage imageNamed:image_seleziona]
  2322. highlightedImage:nil
  2323. action:^(REMenuItem *item) {
  2324. if ([_sectionDataSource.allRecordsDataSource count] > 0)
  2325. [self tableViewSelect:YES];
  2326. }];
  2327. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2328. ordinamento = _directoryOrder;
  2329. if ([ordinamento isEqualToString:@"fileName"]) {
  2330. image = [UIImage imageNamed:image_MenuOrdeyByDate];
  2331. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2332. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2333. nuovoOrdinamento = @"fileDate";
  2334. }
  2335. if ([ordinamento isEqualToString:@"fileDate"]) {
  2336. image = [UIImage imageNamed:image_MenuOrderByFileName];
  2337. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2338. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2339. nuovoOrdinamento = @"fileName";
  2340. }
  2341. if (app.ordinaItem == nil) app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2342. subtitle:titoloAttuale
  2343. image:image
  2344. highlightedImage:nil
  2345. action:^(REMenuItem *item) {
  2346. [self orderTable:nuovoOrdinamento];
  2347. }];
  2348. else app.ordinaItem = [app.ordinaItem initWithTitle:titoloNuovo
  2349. subtitle:titoloAttuale
  2350. image:image
  2351. highlightedImage:nil
  2352. action:^(REMenuItem *item) {
  2353. [self orderTable:nuovoOrdinamento];
  2354. }];
  2355. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2356. ascendente = [CCUtility getAscendingSettings];
  2357. if (ascendente) {
  2358. image = [UIImage imageNamed:image_MenuOrdinamentoDiscendente];
  2359. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2360. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2361. nuovoAscendente = false;
  2362. }
  2363. if (!ascendente) {
  2364. image = [UIImage imageNamed:image_MenuOrdinamentoAscendente];
  2365. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2366. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2367. nuovoAscendente = true;
  2368. }
  2369. if (app.ascendenteItem == nil) app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2370. subtitle:titoloAttuale
  2371. image:image
  2372. highlightedImage:nil
  2373. action:^(REMenuItem *item) {
  2374. [self ascendingTable:nuovoAscendente];
  2375. }];
  2376. else app.ascendenteItem = [app.ascendenteItem initWithTitle:titoloNuovo
  2377. subtitle:titoloAttuale
  2378. image:image
  2379. highlightedImage:nil
  2380. action:^(REMenuItem *item) {
  2381. [self ascendingTable:nuovoAscendente];
  2382. }];
  2383. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2384. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2385. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2386. if (app.alphabeticItem == nil) app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2387. subtitle:@""
  2388. image:[UIImage imageNamed:image_MenuGroupByAlphabetic]
  2389. highlightedImage:nil
  2390. action:^(REMenuItem *item) {
  2391. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2392. else [self tableGroupBy:@"alphabetic"];
  2393. }];
  2394. else app.alphabeticItem = [app.alphabeticItem initWithTitle:titoloNuovo
  2395. subtitle:@""
  2396. image:[UIImage imageNamed:image_MenuGroupByAlphabetic]
  2397. highlightedImage:nil
  2398. action:^(REMenuItem *item) {
  2399. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2400. else [self tableGroupBy:@"alphabetic"];
  2401. }];
  2402. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2403. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2404. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2405. if (app.typefileItem == nil) app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2406. subtitle:@""
  2407. image:[UIImage imageNamed:image_MenuGroupByTypeFile]
  2408. highlightedImage:nil
  2409. action:^(REMenuItem *item) {
  2410. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2411. else [self tableGroupBy:@"typefile"];
  2412. }];
  2413. else app.typefileItem = [app.typefileItem initWithTitle:titoloNuovo
  2414. subtitle:@""
  2415. image:[UIImage imageNamed:image_MenuGroupByTypeFile]
  2416. highlightedImage:nil
  2417. action:^(REMenuItem *item) {
  2418. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2419. else [self tableGroupBy:@"typefile"];
  2420. }];
  2421. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2422. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2423. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2424. if (app.dateItem == nil) app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2425. subtitle:@""
  2426. image:[UIImage imageNamed:image_MenuGroupByDate]
  2427. highlightedImage:nil
  2428. action:^(REMenuItem *item) {
  2429. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2430. else [self tableGroupBy:@"date"];
  2431. }];
  2432. else app.dateItem = [app.dateItem initWithTitle:titoloNuovo
  2433. subtitle:@""
  2434. image:[UIImage imageNamed:image_MenuGroupByDate]
  2435. highlightedImage:nil
  2436. action:^(REMenuItem *item) {
  2437. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2438. else [self tableGroupBy:@"date"];
  2439. }];
  2440. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2441. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2442. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2443. if (app.directoryOnTopItem == nil) app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2444. subtitle:@""
  2445. image:[UIImage imageNamed:image_MenuDirectoryOnTop]
  2446. highlightedImage:nil
  2447. action:^(REMenuItem *item) {
  2448. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2449. else [self directoryOnTop:YES];
  2450. }];
  2451. else app.directoryOnTopItem = [app.directoryOnTopItem initWithTitle:titoloNuovo
  2452. subtitle:@""
  2453. image:[UIImage imageNamed:image_MenuDirectoryOnTop]
  2454. highlightedImage:nil
  2455. action:^(REMenuItem *item) {
  2456. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2457. else [self directoryOnTop:YES];
  2458. }];
  2459. // REMENU --------------------------------------------------------------------------------------------------------------
  2460. if (app.reMainMenu == nil) app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2461. else app.reMainMenu = [app.reMainMenu initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2462. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2463. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2464. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2465. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2466. app.reMainMenu.separatorHeight = 0.5;
  2467. app.reMainMenu.separatorColor = COLOR_SEPARATOR_TABLE;
  2468. app.reMainMenu.backgroundColor = COLOR_BACKGROUND_MENU;
  2469. app.reMainMenu.textColor = [UIColor blackColor];
  2470. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2471. app.reMainMenu.textShadowColor = nil;
  2472. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2473. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2474. app.reMainMenu.highlightedBackgroundColor = COLOR_SELECT_BACKGROUND;
  2475. app.reMainMenu.highlightedSeparatorColor = nil;
  2476. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2477. app.reMainMenu.highlightedTextShadowColor = nil;
  2478. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2479. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2480. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2481. app.reMainMenu.subtitleTextShadowColor = nil;
  2482. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2483. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2484. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2485. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2486. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2487. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2488. app.reMainMenu.borderWidth = 0.3;
  2489. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2490. app.reMainMenu.animationDuration = 0.2;
  2491. app.reMainMenu.closeAnimationDuration = 0.2;
  2492. app.reMainMenu.bounce = NO;
  2493. [app.reMainMenu setClosePreparationBlock:^{
  2494. // Backgroun reMenu (Gesture)
  2495. [_reMenuBackgroundView removeFromSuperview];
  2496. [app.controlCenter disableSingleFingerTap];
  2497. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2498. }];
  2499. }
  2500. - (void)toggleReMainMenu
  2501. {
  2502. if (app.reMainMenu.isOpen) {
  2503. [app.reMainMenu close];
  2504. } else {
  2505. [app.reMainMenu showFromNavigationController:self.navigationController];
  2506. // Backgroun reMenu & (Gesture)
  2507. [self createReMenuBackgroundView:app.reMainMenu];
  2508. [app.controlCenter enableSingleFingerTap:@selector(toggleReMainMenu) target:self];
  2509. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2510. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2511. }
  2512. }
  2513. - (void)createReSelectMenu
  2514. {
  2515. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2516. if (app.deleteItem == nil) app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil)
  2517. subtitle:@""
  2518. image:[UIImage imageNamed:image_deleteSelectedFiles]
  2519. highlightedImage:nil
  2520. action:^(REMenuItem *item) {
  2521. [self deleteSelectionFile];
  2522. }];
  2523. else app.deleteItem = [app.deleteItem initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil)
  2524. subtitle:@""
  2525. image:[UIImage imageNamed:image_deleteSelectedFiles]
  2526. highlightedImage:nil
  2527. action:^(REMenuItem *item) {
  2528. [self deleteSelectionFile];
  2529. }];
  2530. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2531. if (app.moveItem == nil) app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil)
  2532. subtitle:@""
  2533. image:[UIImage imageNamed:image_moveSelectedFiles]
  2534. highlightedImage:nil
  2535. action:^(REMenuItem *item) {
  2536. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2537. }];
  2538. else app.moveItem = [app.moveItem initWithTitle:NSLocalizedString(@"_move_selected_files_", nil)
  2539. subtitle:@""
  2540. image:[UIImage imageNamed:image_moveSelectedFiles]
  2541. highlightedImage:nil
  2542. action:^(REMenuItem *item) {
  2543. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2544. }];
  2545. if (app.isCryptoCloudMode) {
  2546. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2547. if (app.encryptItem == nil) app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil)
  2548. subtitle:@""
  2549. image:[UIImage imageNamed:image_encryptedSelectedFiles]
  2550. highlightedImage:nil
  2551. action:^(REMenuItem *item) {
  2552. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2553. }];
  2554. else app.encryptItem = [app.encryptItem initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil)
  2555. subtitle:@""
  2556. image:[UIImage imageNamed:image_encryptedSelectedFiles]
  2557. highlightedImage:nil
  2558. action:^(REMenuItem *item) {
  2559. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2560. }];
  2561. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2562. if (app.decryptItem == nil) app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil)
  2563. subtitle:@""
  2564. image:[UIImage imageNamed:image_decryptedSelectedFiles]
  2565. highlightedImage:nil
  2566. action:^(REMenuItem *item) {
  2567. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2568. }];
  2569. else app.decryptItem = [app.decryptItem initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil)
  2570. subtitle:@""
  2571. image:[UIImage imageNamed:image_decryptedSelectedFiles]
  2572. highlightedImage:nil
  2573. action:^(REMenuItem *item) {
  2574. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2575. }];
  2576. }
  2577. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2578. if (app.downloadItem == nil) app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_", nil)
  2579. subtitle:@""
  2580. image:[UIImage imageNamed:image_downloadSelectedFiles]
  2581. highlightedImage:nil
  2582. action:^(REMenuItem *item) {
  2583. [self downloadSelectedFiles];
  2584. }];
  2585. else app.downloadItem = [app.downloadItem initWithTitle:NSLocalizedString(@"_download_selected_files_", nil)
  2586. subtitle:@""
  2587. image:[UIImage imageNamed:image_downloadSelectedFiles]
  2588. highlightedImage:nil
  2589. action:^(REMenuItem *item) {
  2590. [self downloadSelectedFiles];
  2591. }];
  2592. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2593. if (app.saveItem == nil) app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil)
  2594. subtitle:@""
  2595. image:[UIImage imageNamed:image_saveSelectedFiles]
  2596. highlightedImage:nil
  2597. action:^(REMenuItem *item) {
  2598. [self saveSelectedFiles];
  2599. }];
  2600. else app.saveItem = [app.saveItem initWithTitle:NSLocalizedString(@"_save_selected_files_", nil)
  2601. subtitle:@""
  2602. image:[UIImage imageNamed:image_saveSelectedFiles]
  2603. highlightedImage:nil
  2604. action:^(REMenuItem *item) {
  2605. [self saveSelectedFiles];
  2606. }];
  2607. // REMENU --------------------------------------------------------------------------------------------------------------
  2608. if (app.isCryptoCloudMode) {
  2609. if (app.reSelectMenu == nil)
  2610. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2611. else
  2612. app.reSelectMenu = [app.reSelectMenu initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2613. } else {
  2614. if (app.reSelectMenu == nil)
  2615. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2616. else
  2617. app.reSelectMenu = [app.reSelectMenu initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2618. }
  2619. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2620. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2621. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2622. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2623. app.reSelectMenu.separatorHeight = 0.5;
  2624. app.reSelectMenu.separatorColor = COLOR_SEPARATOR_TABLE;
  2625. app.reSelectMenu.backgroundColor = COLOR_BACKGROUND_MENU;
  2626. app.reSelectMenu.textColor = [UIColor blackColor];
  2627. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2628. app.reSelectMenu.textShadowColor = nil;
  2629. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2630. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2631. app.reSelectMenu.highlightedBackgroundColor = COLOR_SELECT_BACKGROUND;
  2632. app.reSelectMenu.highlightedSeparatorColor = nil;
  2633. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2634. app.reSelectMenu.highlightedTextShadowColor = nil;
  2635. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2636. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2637. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2638. app.reSelectMenu.subtitleTextShadowColor = nil;
  2639. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2640. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2641. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2642. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2643. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2644. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2645. app.reSelectMenu.borderWidth = 0.3;
  2646. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2647. app.reSelectMenu.closeAnimationDuration = 0.2;
  2648. app.reSelectMenu.animationDuration = 0.2;
  2649. app.reSelectMenu.bounce = NO;
  2650. [app.reSelectMenu setClosePreparationBlock:^{
  2651. // Backgroun reMenu (Gesture)
  2652. [_reMenuBackgroundView removeFromSuperview];
  2653. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2654. }];
  2655. }
  2656. - (void)toggleReSelectMenu
  2657. {
  2658. if (app.reSelectMenu.isOpen) {
  2659. [app.reSelectMenu close];
  2660. } else {
  2661. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2662. // Backgroun reMenu & (Gesture)
  2663. [self createReMenuBackgroundView:app.reSelectMenu];
  2664. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2665. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2666. }
  2667. }
  2668. #pragma --------------------------------------------------------------------------------------------
  2669. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2670. #pragma --------------------------------------------------------------------------------------------
  2671. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2672. {
  2673. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2674. UITableView *tableView = (UITableView*)self.view;
  2675. CGPoint touchPoint = [recognizer locationInView:self.view];
  2676. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2677. if (indexPath)
  2678. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2679. else
  2680. _metadata = nil;
  2681. [self becomeFirstResponder];
  2682. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2683. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2684. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2685. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2686. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2687. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2688. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2689. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2690. if (app.isCryptoCloudMode)
  2691. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2692. else
  2693. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2694. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2695. [menuController setMenuVisible:YES animated:YES];
  2696. }
  2697. }
  2698. - (BOOL)canBecomeFirstResponder
  2699. {
  2700. return YES;
  2701. }
  2702. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2703. {
  2704. // For copy file, copy files, Open in ... :
  2705. //
  2706. // NO Directory
  2707. // NO Error Passcode
  2708. // NO In Session mode (download/upload)
  2709. // NO Template
  2710. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2711. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2712. // NO Cryptated with Title lenght = 0
  2713. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2714. return YES;
  2715. }
  2716. return NO;
  2717. }
  2718. if (@selector(copyFiles:) == action) {
  2719. if (_isSelectedMode) {
  2720. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2721. for (CCMetadata *metadata in selectedMetadatas) {
  2722. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2723. // NO Cryptated with Title lenght = 0
  2724. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2725. return YES;
  2726. }
  2727. }
  2728. }
  2729. return NO;
  2730. }
  2731. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2732. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2733. NSArray *items = [pasteboard items];
  2734. if ([items count] == 1) {
  2735. // key : it.twsweb.Crypto-Cloud.CCMetadata Value : (NSData) metadata
  2736. NSDictionary *dic = [items objectAtIndex:0];
  2737. NSData *dataMetadata = [dic objectForKey:@"it.twsweb.Crypto-Cloud.CCMetadata"];
  2738. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2739. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2740. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2741. if (directoryUser) {
  2742. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2743. return YES;
  2744. }
  2745. return NO;
  2746. } else return NO;
  2747. }
  2748. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2749. BOOL isValid = NO;
  2750. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2751. NSArray *items = [pasteboard items];
  2752. if ([items count] <= 1) return NO;
  2753. for (NSDictionary *dic in items) {
  2754. // key : it.twsweb.Crypto-Cloud.CCMetadata Value : (NSData) metadata
  2755. NSData *dataMetadata = [dic objectForKey:@"it.twsweb.Crypto-Cloud.CCMetadata"];
  2756. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2757. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2758. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2759. if (directoryUser) {
  2760. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2761. isValid = YES;
  2762. }
  2763. }
  2764. return isValid;
  2765. }
  2766. return NO;
  2767. }
  2768. /************************************ COPY ************************************/
  2769. - (void)copyFile:(id)sender
  2770. {
  2771. // Remove all item
  2772. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2773. pasteboard.items = [[NSArray alloc] init];
  2774. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2775. [self copyFileToPasteboard:_metadata];
  2776. } else {
  2777. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2778. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2779. }
  2780. }
  2781. - (void)copyFiles:(id)sender
  2782. {
  2783. // Remove all item
  2784. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2785. pasteboard.items = [[NSArray alloc] init];
  2786. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2787. for (CCMetadata *metadata in selectedMetadatas) {
  2788. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2789. [self copyFileToPasteboard:metadata];
  2790. } else {
  2791. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2792. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2793. }
  2794. }
  2795. [self tableViewSelect:NO];
  2796. }
  2797. - (void)copyFileToPasteboard:(CCMetadata *)metadata
  2798. {
  2799. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2800. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2801. // key : it.twsweb.Crypto-Cloud.CCMetadata Value : (NSData) metadata
  2802. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata], @"it.twsweb.Crypto-Cloud.CCMetadata",nil];
  2803. [items addObject:item];
  2804. [pasteboard setItems:items];
  2805. }
  2806. /************************************ OPEN IN ... ************************************/
  2807. - (void)openinFile:(id)sender
  2808. {
  2809. [self openIn:_metadata];
  2810. }
  2811. /************************************ PASTE ************************************/
  2812. - (void)pasteFile:(id)sender
  2813. {
  2814. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2815. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2816. }
  2817. - (void)pasteFileEncrypted:(id)sender
  2818. {
  2819. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2820. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2821. }
  2822. - (void)pasteFiles:(id)sender
  2823. {
  2824. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2825. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2826. }
  2827. - (void)pasteFilesEncrypted:(id)sender
  2828. {
  2829. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2830. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2831. }
  2832. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2833. {
  2834. for (NSDictionary *dic in items) {
  2835. // key : it.twsweb.Crypto-Cloud.CCMetadata
  2836. // Value : (NSData) metadata
  2837. NSData *dataMetadata = [dic objectForKey:@"it.twsweb.Crypto-Cloud.CCMetadata"];
  2838. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2839. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2840. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2841. if (directoryUser) {
  2842. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]]) {
  2843. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2844. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2845. }
  2846. }
  2847. }
  2848. }
  2849. #pragma --------------------------------------------------------------------------------------------
  2850. #pragma mark ===== Lock Passcode =====
  2851. #pragma --------------------------------------------------------------------------------------------
  2852. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2853. {
  2854. return _failedAttempts;
  2855. }
  2856. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2857. {
  2858. return _lockUntilDate;
  2859. }
  2860. - (void)passcodeViewCloseButtonPressed:(id)sender
  2861. {
  2862. [self dismissViewControllerAnimated:YES completion:nil];
  2863. }
  2864. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2865. {
  2866. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2867. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2868. _lockUntilDate = nil;
  2869. _failedAttempts = 0;
  2870. aResultHandler(YES);
  2871. } else aResultHandler(NO);
  2872. } else aResultHandler(YES);
  2873. }
  2874. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2875. {
  2876. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2877. switch (aViewController.type) {
  2878. case BKPasscodeViewControllerCheckPasscodeType: {
  2879. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2880. CCCrypto *crypto = [[CCCrypto alloc] init];
  2881. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2882. if ([crypto verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2883. // scriviamo il passcode
  2884. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2885. [self readFolderWithForced:YES];
  2886. } else {
  2887. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2888. [alertView show];
  2889. }
  2890. }
  2891. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2892. // possiamo procedere alla prossima directory
  2893. [self performSegueDirectoryWithControlPasscode:false];
  2894. // avviamo la sessione Passcode Lock con now
  2895. app.sessionePasscodeLock = [NSDate date];
  2896. }
  2897. // disattivazione lock cartella
  2898. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2899. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2900. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  2901. if ([CCCoreData setDirectoryUnLock:lockServerUrl activeAccount:app.activeAccount] == NO) {
  2902. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2903. }
  2904. [self.tableView reloadData];
  2905. }
  2906. }
  2907. break;
  2908. default:
  2909. break;
  2910. }
  2911. }
  2912. - (void)comandoLockPassword
  2913. {
  2914. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2915. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  2916. // se non è abilitato il Lock Passcode esci
  2917. if ([[CCUtility getBlockCode] length] == 0) {
  2918. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2919. [alertView show];
  2920. return;
  2921. }
  2922. // se è richiesta la disattivazione si chiede la password
  2923. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2924. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2925. viewController.delegate = self;
  2926. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2927. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2928. viewController.inputViewTitlePassword = YES;
  2929. if ([CCUtility getSimplyBlockCode]) {
  2930. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2931. viewController.passcodeInputView.maximumLength = 6;
  2932. } else {
  2933. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2934. viewController.passcodeInputView.maximumLength = 64;
  2935. }
  2936. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:BKPasscodeKeychainServiceName];
  2937. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2938. viewController.touchIDManager = touchIDManager;
  2939. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2940. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2941. viewController.navigationItem.leftBarButtonItem.tintColor = COLOR_CRYPTOCLOUD;
  2942. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2943. [self presentViewController:navigationController animated:YES completion:nil];
  2944. return;
  2945. }
  2946. // ---------------- ACTIVATE PASSWORD
  2947. if([CCCoreData setDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2948. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2949. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2950. } else {
  2951. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2952. }
  2953. }
  2954. #pragma mark -
  2955. #pragma --------------------------------------------------------------------------------------------
  2956. #pragma mark ===== Swipe Tablet -> menu =====
  2957. #pragma --------------------------------------------------------------------------------------------
  2958. // more
  2959. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  2960. return NSLocalizedString(@"_more_", nil);
  2961. }
  2962. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  2963. {
  2964. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2965. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2966. NSString *titoloCriptaDecripta, *titoloOffline, *titoloLock, *titleOfflineFolder;
  2967. BOOL offlineFolder = NO;
  2968. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  2969. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  2970. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount]) titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  2971. else titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  2972. NSString *offlineServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  2973. if (_metadata.directory && [CCCoreData isOfflineDirectoryServerUrl:offlineServerUrl activeAccount:app.activeAccount]) {
  2974. titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  2975. offlineFolder = YES;
  2976. } else titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  2977. if (_metadata.directory) {
  2978. // calcolo lockServerUrl
  2979. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  2980. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2981. else titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2982. }
  2983. /******************************************* AHKActionSheet *******************************************/
  2984. UIImage *iconHeader;
  2985. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  2986. actionSheet.animationDuration = 0.2;
  2987. actionSheet.blurRadius = 0.0f;
  2988. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  2989. actionSheet.buttonHeight = 50.0;
  2990. actionSheet.cancelButtonHeight = 50.0f;
  2991. actionSheet.separatorHeight = 5.0f;
  2992. actionSheet.automaticallyTintButtonImages = @(NO);
  2993. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName:COLOR_CRYPTOCLOUD };
  2994. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName:COLOR_TEXT_ANTHRACITE };
  2995. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:COLOR_BRAND };
  2996. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:12], NSForegroundColorAttributeName:COLOR_TEXT_ANTHRACITE };
  2997. actionSheet.separatorColor = COLOR_SEPARATOR_TABLE;
  2998. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2999. /******************************************* DIRECTORY *******************************************/
  3000. if (_metadata.directory) {
  3001. UIImage *iconHeader;
  3002. BOOL lockDirectory = NO;
  3003. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  3004. NSString *upDir = [CCUtility deletingLastPathComponentFromServerUrl:dirServerUrl];
  3005. NSString *homeDir = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  3006. // Directory bloccata ?
  3007. if ([CCCoreData isDirectoryLock:dirServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3008. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3009. NSString *cameraUploadFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount];
  3010. NSString *cameraUploadFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3011. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3012. image: iconHeader
  3013. backgroundColor: COLOR_BACKGROUND_MENU
  3014. height: 50.0
  3015. type: AHKActionSheetButtonTypeDisabled
  3016. handler: nil
  3017. ];
  3018. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3019. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3020. image:[UIImage imageNamed:image_actionSheetRename]
  3021. backgroundColor:[UIColor whiteColor]
  3022. height: 50.0
  3023. type:AHKActionSheetButtonTypeDefault
  3024. handler:^(AHKActionSheet *as) {
  3025. // close swipe
  3026. [self setEditing:NO animated:YES];
  3027. //chiediamo il nome del file
  3028. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3029. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3030. alertView.tag = alertRename;
  3031. UITextField *textField = [alertView textFieldAtIndex:0];
  3032. textField.text = _metadata.fileNamePrint;
  3033. [alertView show];
  3034. }];
  3035. }
  3036. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3037. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3038. image:[UIImage imageNamed:image_actionSheetMove]
  3039. backgroundColor:[UIColor whiteColor]
  3040. height: 50.0
  3041. type:AHKActionSheetButtonTypeDefault
  3042. handler:^(AHKActionSheet *as) {
  3043. // close swipe
  3044. [self setEditing:NO animated:YES];
  3045. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3046. }];
  3047. }
  3048. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3049. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3050. image:[UIImage imageNamed:image_actionSheetCrypto]
  3051. backgroundColor:[UIColor whiteColor]
  3052. height: 50.0
  3053. type:AHKActionSheetButtonTypeEncrypted
  3054. handler:^(AHKActionSheet *as) {
  3055. // close swipe
  3056. [self setEditing:NO animated:YES];
  3057. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3058. }];
  3059. }
  3060. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES)) {
  3061. [actionSheet addButtonWithTitle:titoloLock
  3062. image:[UIImage imageNamed:image_actionSheetLock]
  3063. backgroundColor:[UIColor whiteColor]
  3064. height: 50.0
  3065. type:AHKActionSheetButtonTypeEncrypted
  3066. handler:^(AHKActionSheet *as) {
  3067. // close swipe
  3068. [self setEditing:NO animated:YES];
  3069. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3070. }];
  3071. }
  3072. if (_metadata.cryptated == NO && app.hasServerShareSupport && !lockDirectory) {
  3073. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3074. image:[UIImage imageNamed:image_actionSheetShare]
  3075. backgroundColor:[UIColor whiteColor]
  3076. height: 50.0
  3077. type:AHKActionSheetButtonTypeDefault
  3078. handler:^(AHKActionSheet *as) {
  3079. // close swipe
  3080. [self setEditing:NO animated:YES];
  3081. [self openWindowShare:_metadata];
  3082. }];
  3083. }
  3084. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && _metadata.cryptated == NO) {
  3085. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3086. image:[UIImage imageNamed:image_folderphotocamera]
  3087. backgroundColor:[UIColor whiteColor]
  3088. height: 50.0
  3089. type:AHKActionSheetButtonTypeDefault
  3090. handler:^(AHKActionSheet *as) {
  3091. // close swipe
  3092. [self setEditing:NO animated:YES];
  3093. // Settings new folder Automatatic upload
  3094. NSString *oldPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3095. [CCCoreData setCameraUploadFolderName:_metadata.fileName activeAccount:app.activeAccount];
  3096. [CCCoreData setCameraUploadFolderPath:serverUrl activeUrl:app.activeUrl activeAccount:app.activeAccount];
  3097. [CCCoreData clearDateReadDirectory:oldPath activeAccount:app.activeAccount];
  3098. if (app.activeAccount.length > 0 && app.activePhotosCameraUpload)
  3099. [app.activePhotosCameraUpload reloadDatasourceForced];
  3100. [self readFolderWithForced:YES];
  3101. }];
  3102. }
  3103. if (!lockDirectory && ([upDir isEqualToString:homeDir] || ![CCCoreData isOfflineDirectoryServerUrl:upDir activeAccount:app.activeAccount]) && !_metadata.cryptated) {
  3104. [actionSheet addButtonWithTitle:titleOfflineFolder
  3105. image:[UIImage imageNamed:image_actionSheetOffline]
  3106. backgroundColor:[UIColor whiteColor]
  3107. height: 50.0
  3108. type:AHKActionSheetButtonTypeDefault
  3109. handler:^(AHKActionSheet *as) {
  3110. // close swipe
  3111. [self setEditing:NO animated:YES];
  3112. if (offlineFolder == NO) {
  3113. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"",nil) message:NSLocalizedString(@"_offline_folder_confirm_",nil) delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3114. alertView.tag = alertOfflineFolder;
  3115. [alertView show];
  3116. } else {
  3117. // remove tag offline for all folder/subfolder/file
  3118. NSArray *directories = [CCCoreData getOfflineDirectoryActiveAccount:app.activeAccount];
  3119. for (TableDirectory *directory in directories)
  3120. if ([directory.serverUrl containsString:dirServerUrl]) {
  3121. [CCCoreData setOfflineDirectoryServerUrl:directory.serverUrl offline:NO activeAccount:app.activeAccount];
  3122. [CCCoreData removeOfflineAllFileFromServerUrl:directory.serverUrl activeAccount:app.activeAccount];
  3123. }
  3124. [self performSelector:@selector(reloadDatasource) withObject:nil];
  3125. }
  3126. }];
  3127. }
  3128. [actionSheet show];
  3129. }
  3130. /******************************************* FILE *******************************************/
  3131. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3132. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3133. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3134. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3135. else
  3136. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3137. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3138. image: iconHeader
  3139. backgroundColor: COLOR_BACKGROUND_MENU
  3140. height: 50.0
  3141. type: AHKActionSheetButtonTypeDisabled
  3142. handler: nil
  3143. ];
  3144. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3145. image:[UIImage imageNamed:image_actionSheetRename]
  3146. backgroundColor:[UIColor whiteColor]
  3147. height: 50.0
  3148. type:AHKActionSheetButtonTypeDefault
  3149. handler:^(AHKActionSheet *as) {
  3150. // close swipe
  3151. [self setEditing:NO animated:YES];
  3152. //chiediamo il nome del file
  3153. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3154. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3155. alertView.tag = alertRename;
  3156. UITextField *textField = [alertView textFieldAtIndex:0];
  3157. textField.text = _metadata.fileNamePrint;
  3158. [alertView show];
  3159. }];
  3160. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3161. image:[UIImage imageNamed:image_actionSheetMove]
  3162. backgroundColor:[UIColor whiteColor]
  3163. height: 50.0
  3164. type:AHKActionSheetButtonTypeDefault
  3165. handler:^(AHKActionSheet *as) {
  3166. // close swipe
  3167. [self setEditing:NO animated:YES];
  3168. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3169. }];
  3170. [actionSheet addButtonWithTitle:NSLocalizedString(@"_reload_", nil)
  3171. image:[UIImage imageNamed:image_actionSheetReload]
  3172. backgroundColor:[UIColor whiteColor]
  3173. height: 50.0
  3174. type:AHKActionSheetButtonTypeDefault
  3175. handler:^(AHKActionSheet *as) {
  3176. // close swipe
  3177. [self setEditing:NO animated:YES];
  3178. [self performSelector:@selector(reloadFile:) withObject:_metadata];
  3179. }];
  3180. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3181. image:[UIImage imageNamed:image_actionSheetOpenIn]
  3182. backgroundColor:[UIColor whiteColor]
  3183. height: 50.0
  3184. type:AHKActionSheetButtonTypeDefault
  3185. handler:^(AHKActionSheet *as) {
  3186. // close swipe
  3187. [self setEditing:NO animated:YES];
  3188. [self performSelector:@selector(openIn:) withObject:_metadata];
  3189. }];
  3190. if (_metadata.cryptated == NO && app.hasServerShareSupport) {
  3191. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3192. image:[UIImage imageNamed:image_actionSheetShare]
  3193. backgroundColor:[UIColor whiteColor]
  3194. height: 50.0
  3195. type:AHKActionSheetButtonTypeDefault
  3196. handler:^(AHKActionSheet *as) {
  3197. // close swipe
  3198. [self setEditing:NO animated:YES];
  3199. [self openWindowShare:_metadata];
  3200. }];
  3201. }
  3202. if (app.isCryptoCloudMode) {
  3203. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3204. image:[UIImage imageNamed:image_actionSheetCrypto]
  3205. backgroundColor:[UIColor whiteColor]
  3206. height: 50.0
  3207. type:AHKActionSheetButtonTypeEncrypted
  3208. handler:^(AHKActionSheet *as) {
  3209. // close swipe
  3210. [self setEditing:NO animated:YES];
  3211. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3212. }];
  3213. }
  3214. if (!_metadata.cryptated) {
  3215. [actionSheet addButtonWithTitle:titoloOffline
  3216. image:[UIImage imageNamed:image_actionSheetOffline]
  3217. backgroundColor:[UIColor whiteColor]
  3218. height: 50.0
  3219. type:AHKActionSheetButtonTypeDefault
  3220. handler:^(AHKActionSheet *as) {
  3221. // close swipe
  3222. [self setEditing:NO animated:YES];
  3223. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount]) {
  3224. [self removeOffline:_metadata];
  3225. } else {
  3226. [self addOffline:_metadata];
  3227. }
  3228. }];
  3229. }
  3230. [actionSheet addButtonWithTitle:NSLocalizedString(@"_add_local_", nil)
  3231. image:[UIImage imageNamed:image_actionSheetLocal]
  3232. backgroundColor:[UIColor whiteColor]
  3233. height: 50.0
  3234. type:AHKActionSheetButtonTypeDefault
  3235. handler:^(AHKActionSheet *as) {
  3236. // close swipe
  3237. [self setEditing:NO animated:YES];
  3238. [self performSelector:@selector(addLocal:) withObject:_metadata];
  3239. }];
  3240. [actionSheet show];
  3241. }
  3242. /******************************************* TEMPLATE *******************************************/
  3243. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3244. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3245. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3246. image: iconHeader
  3247. backgroundColor: COLOR_BACKGROUND_MENU
  3248. height: 50.0
  3249. type: AHKActionSheetButtonTypeDisabled
  3250. handler: nil
  3251. ];
  3252. if ([_metadata.model isEqualToString:@"note"]) {
  3253. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3254. image:[UIImage imageNamed:image_actionSheetRename]
  3255. backgroundColor:[UIColor whiteColor]
  3256. height: 50.0
  3257. type:AHKActionSheetButtonTypeDefault
  3258. handler:^(AHKActionSheet *as) {
  3259. // close swipe
  3260. [self setEditing:NO animated:YES];
  3261. //chiediamo il nome del file
  3262. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3263. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3264. alertView.tag = alertRename;
  3265. UITextField *textField = [alertView textFieldAtIndex:0];
  3266. textField.text = _metadata.fileNamePrint;
  3267. [alertView show];
  3268. }];
  3269. }
  3270. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3271. image:[UIImage imageNamed:image_actionSheetMove]
  3272. backgroundColor:[UIColor whiteColor]
  3273. height: 50.0
  3274. type:AHKActionSheetButtonTypeDefault
  3275. handler:^(AHKActionSheet *as) {
  3276. // close swipe
  3277. [self setEditing:NO animated:YES];
  3278. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3279. }];
  3280. [actionSheet addButtonWithTitle:titoloOffline
  3281. image:[UIImage imageNamed:image_actionSheetOffline]
  3282. backgroundColor:[UIColor whiteColor]
  3283. height: 50.0
  3284. type:AHKActionSheetButtonTypeDefault
  3285. handler:^(AHKActionSheet *as) {
  3286. // close swipe
  3287. [self setEditing:NO animated:YES];
  3288. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount])
  3289. [self removeOffline:_metadata];
  3290. else
  3291. [self addOffline:_metadata];
  3292. }];
  3293. [actionSheet addButtonWithTitle:NSLocalizedString(@"_add_local_", nil)
  3294. image:[UIImage imageNamed:image_actionSheetLocal]
  3295. backgroundColor:[UIColor whiteColor]
  3296. height: 50.0
  3297. type:AHKActionSheetButtonTypeDefault
  3298. handler:^(AHKActionSheet *as) {
  3299. // close swipe
  3300. [self setEditing:NO animated:YES];
  3301. [self performSelector:@selector(addLocal:) withObject:_metadata];
  3302. }];
  3303. [actionSheet show];
  3304. }
  3305. }
  3306. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3307. {
  3308. return NSLocalizedString(@"_delete_", nil);
  3309. }
  3310. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3311. {
  3312. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3313. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3314. else return YES;
  3315. }
  3316. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3317. {
  3318. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3319. if (metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3320. else return UITableViewCellEditingStyleDelete;
  3321. }
  3322. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3323. {
  3324. BOOL lockDirectory = NO;
  3325. // Directory locked ?
  3326. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account] addServerUrl:_metadata.fileNameData];
  3327. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3328. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3329. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  3330. return;
  3331. }
  3332. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3333. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3334. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3335. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3336. style:UIAlertActionStyleDestructive
  3337. handler:^(UIAlertAction *action) {
  3338. [self performSelector:@selector(deleteFile) withObject:nil];
  3339. }]];
  3340. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3341. style:UIAlertActionStyleCancel
  3342. handler:^(UIAlertAction *action) {
  3343. [alertController dismissViewControllerAnimated:YES completion:nil];
  3344. }]];
  3345. alertController.popoverPresentationController.sourceView = self.view;
  3346. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3347. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3348. [alertController.view layoutIfNeeded];
  3349. [self presentViewController:alertController animated:YES completion:nil];
  3350. }
  3351. }
  3352. #pragma --------------------------------------------------------------------------------------------
  3353. #pragma mark - ==== Datasource ====
  3354. #pragma --------------------------------------------------------------------------------------------
  3355. - (void)clearDateReadDataSource:(NSNotification *)notification
  3356. {
  3357. _dateReadDataSource = Nil;
  3358. }
  3359. - (void)reloadDatasource
  3360. {
  3361. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  3362. }
  3363. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID selector:(NSString *)selector
  3364. {
  3365. // test
  3366. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3367. return;
  3368. // Search Mode
  3369. if(_isSearchMode) {
  3370. if ([selector length] == 0 || [selector isEqualToString:selectorSearch]) {
  3371. _sectionDataSource = [CCSection creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3372. } else {
  3373. [self readFolderWithForced:NO];
  3374. }
  3375. [self tableViewReload];
  3376. [self setTitleBackgroundTableView:nil];
  3377. [app updateApplicationIconBadgeNumber];
  3378. return;
  3379. }
  3380. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3381. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3382. if ([selector isEqualToString:selectorDownloadOffline]) {
  3383. [app.controlCenter reloadDatasource];
  3384. } else {
  3385. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3386. if (main) {
  3387. [main reloadDatasource];
  3388. } else {
  3389. [self tableViewReload];
  3390. [app.controlCenter reloadDatasource];
  3391. }
  3392. }
  3393. return;
  3394. }
  3395. // Offline folder ?
  3396. _isOfflineServerUrl = [CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount];
  3397. [app.controlCenter reloadDatasource];
  3398. // Settaggio variabili per le ottimizzazioni
  3399. _directoryGroupBy = [CCUtility getGroupBySettings];
  3400. _directoryOrder = [CCUtility getOrderSettings];
  3401. // Controllo data lettura Data Source
  3402. NSDate *dateDateRecordDirectory = [CCCoreData getDateReadDirectoryID:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount] activeAccount:app.activeAccount];
  3403. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3404. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3405. _dateReadDataSource = [NSDate date];
  3406. // Data Source
  3407. NSArray *recordsTableMetadata = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@)", app.activeAccount, [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount]] fieldOrder:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3408. _sectionDataSource = [CCSection creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3409. } else {
  3410. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3411. }
  3412. [self tableViewReload];
  3413. [self setTitleBackgroundTableView];
  3414. [app updateApplicationIconBadgeNumber];
  3415. }
  3416. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3417. {
  3418. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3419. if (selectedRows.count > 0) {
  3420. for (NSIndexPath *selectionIndex in selectedRows) {
  3421. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3422. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3423. [metadatas addObject:metadata];
  3424. }
  3425. }
  3426. return metadatas;
  3427. }
  3428. - (CCMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3429. {
  3430. NSInteger section = indexPath.section + 1;
  3431. NSInteger row = indexPath.row + 1;
  3432. NSInteger totSections =[_sectionDataSource.sections count] ;
  3433. if ((totSections < section) || (section > totSections)) {
  3434. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3435. return nil;
  3436. }
  3437. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3438. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3439. if (fileIDs) {
  3440. NSInteger totRows =[fileIDs count] ;
  3441. if ((totRows < row) || (row > totRows)) {
  3442. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3443. return nil;
  3444. }
  3445. } else {
  3446. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3447. return nil;
  3448. }
  3449. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3450. return [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3451. }
  3452. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3453. {
  3454. NSInteger totSections =[_sectionDataSource.sections count] ;
  3455. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3456. #if DEBUG
  3457. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3458. [alertView show];
  3459. #endif
  3460. return nil;
  3461. }
  3462. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3463. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3464. }
  3465. #pragma --------------------------------------------------------------------------------------------
  3466. #pragma mark - ==== Table ====
  3467. #pragma --------------------------------------------------------------------------------------------
  3468. - (void)tableViewSelect:(BOOL)edit
  3469. {
  3470. // chiudiamo eventuali swipe aperti
  3471. if (edit) [self.tableView setEditing:NO animated:NO];
  3472. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3473. [self.tableView setEditing:edit animated:YES];
  3474. _isSelectedMode = edit;
  3475. if (edit)
  3476. [self setUINavigationBarSelected];
  3477. else
  3478. [self setUINavigationBarDefault];
  3479. [self setTitle];
  3480. }
  3481. - (void)tableViewReload
  3482. {
  3483. // ricordiamoci le row selezionate
  3484. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3485. [self.tableView reloadData];
  3486. for (NSIndexPath *path in indexPaths)
  3487. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3488. [self setTableViewFooter];
  3489. if (self.tableView.editing)
  3490. [self setTitle];
  3491. }
  3492. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3493. {
  3494. return 60;
  3495. }
  3496. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3497. {
  3498. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3499. }
  3500. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3501. {
  3502. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3503. }
  3504. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3505. {
  3506. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3507. NSString *sectionTitle = [sections objectAtIndex:section];
  3508. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3509. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3510. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3511. return 20.f;
  3512. }
  3513. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3514. {
  3515. float shift;
  3516. UIVisualEffectView *visualEffectView;
  3517. // Titolo
  3518. NSString *titleSection;
  3519. // Controllo
  3520. if ([_sectionDataSource.sections count] == 0)
  3521. return nil;
  3522. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3523. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3524. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3525. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3526. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3527. else titleSection = NSLocalizedString(titleSection,nil);
  3528. // Formato titolo
  3529. NSString *currentDevice = [CCUtility currentDevice];
  3530. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3531. visualEffectView = [[UIVisualEffectView alloc] init];
  3532. visualEffectView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  3533. } else {
  3534. UIVisualEffect *blurEffect;
  3535. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3536. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3537. visualEffectView.backgroundColor = COLOR_GROUPBY_BAR;
  3538. }
  3539. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3540. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3541. else shift = - 20;
  3542. } else shift = - 10;
  3543. // Title
  3544. UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3545. titleLabel.backgroundColor=[UIColor clearColor];
  3546. titleLabel.textColor = COLOR_TEXT_ANTHRACITE;
  3547. titleLabel.font = [UIFont systemFontOfSize:12];
  3548. titleLabel.textAlignment = NSTextAlignmentLeft;
  3549. titleLabel.text = titleSection;
  3550. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3551. [visualEffectView addSubview:titleLabel];
  3552. // Elements
  3553. UILabel *elementLabel=[[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3554. elementLabel.backgroundColor=[UIColor clearColor];
  3555. elementLabel.textColor = COLOR_TEXT_ANTHRACITE;
  3556. elementLabel.font = [UIFont systemFontOfSize:12];
  3557. elementLabel.textAlignment = NSTextAlignmentRight;
  3558. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3559. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3560. NSUInteger rowsCount = [metadatas count];
  3561. if (rowsCount == 0) return nil;
  3562. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3563. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3564. [visualEffectView addSubview:elementLabel];
  3565. return visualEffectView;
  3566. }
  3567. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3568. {
  3569. return [_sectionDataSource.sections indexOfObject:title];
  3570. }
  3571. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3572. {
  3573. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3574. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3575. else
  3576. return nil;
  3577. }
  3578. /*
  3579. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3580. {
  3581. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3582. }
  3583. }
  3584. */
  3585. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3586. {
  3587. NSString *typeCell;
  3588. NSString *dataFile;
  3589. NSString *lunghezzaFile;
  3590. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3591. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  3592. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3593. else typeCell = @"CellMainTransfer";
  3594. if (!metadata)
  3595. return [tableView dequeueReusableCellWithIdentifier:typeCell];
  3596. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3597. // separator
  3598. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3599. // change color selection
  3600. UIView *selectionColor = [[UIView alloc] init];
  3601. selectionColor.backgroundColor = COLOR_SELECT_BACKGROUND;
  3602. cell.selectedBackgroundView = selectionColor;
  3603. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3604. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = COLOR_TRANSFER_BACKGROUND;
  3605. // ----------------------------------------------------------------------------------------------------------
  3606. // DEFAULT
  3607. // ----------------------------------------------------------------------------------------------------------
  3608. cell.fileImageView.image = nil;
  3609. cell.statusImageView.image = nil;
  3610. cell.offlineImageView.image = nil;
  3611. cell.synchronizedImageView.image = nil;
  3612. cell.sharedImageView.image = nil;
  3613. cell.labelTitle.enabled = YES;
  3614. cell.labelTitle.text = @"";
  3615. cell.labelInfoFile.enabled = YES;
  3616. cell.labelInfoFile.text = @"";
  3617. cell.progressView.progress = 0.0;
  3618. cell.progressView.hidden = YES;
  3619. cell.cancelTaskButton.hidden = YES;
  3620. cell.reloadTaskButton.hidden = YES;
  3621. cell.stopTaskButton.hidden = YES;
  3622. // colori e font
  3623. if (metadata.cryptated) {
  3624. cell.labelTitle.textColor = COLOR_CRYPTOCLOUD;
  3625. cell.labelInfoFile.textColor = [UIColor blackColor];
  3626. } else {
  3627. cell.labelTitle.textColor = COLOR_TEXT_ANTHRACITE;
  3628. cell.labelInfoFile.textColor = [UIColor blackColor];
  3629. }
  3630. // ----------------------------------------------------------------------------------------------------------
  3631. // File Name & Folder
  3632. // ----------------------------------------------------------------------------------------------------------
  3633. // nome del file
  3634. cell.labelTitle.text = metadata.fileNamePrint;
  3635. // è una directory
  3636. if (metadata.directory) {
  3637. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3638. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3639. lunghezzaFile = @" ";
  3640. // ----------------------------------------------------------------------------------------------------------
  3641. // Offline Folder
  3642. // ----------------------------------------------------------------------------------------------------------
  3643. NSString *directoryServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:metadata.fileNameData];
  3644. BOOL isOfflineDirectory = [CCCoreData isOfflineDirectoryServerUrl:directoryServerUrl activeAccount:app.activeAccount];
  3645. // Verify Offline
  3646. if (_isOfflineServerUrl == YES && isOfflineDirectory == NO) {
  3647. [CCCoreData setOfflineDirectoryServerUrl:directoryServerUrl offline:YES activeAccount:app.activeAccount];
  3648. isOfflineDirectory = YES;
  3649. }
  3650. if (isOfflineDirectory) {
  3651. // Image Offline
  3652. if (metadata.cryptated) cell.offlineImageView.image = [UIImage imageNamed:image_offlinecrypto];
  3653. else cell.offlineImageView.image = [UIImage imageNamed:image_offline];
  3654. // Animation synchronized gif
  3655. if ([[CCOfflineFileFolder sharedOfflineFileFolder] offlineFolderAnimationDirectory:[[NSArray alloc] initWithObjects:directoryServerUrl, nil] setGraphicsFolder:NO]) {
  3656. NSURL *myURL;
  3657. if (metadata.cryptated) myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  3658. else myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  3659. cell.synchronizedImageView.image = [UIImage animatedImageWithAnimatedGIFURL:myURL];
  3660. }
  3661. }
  3662. } else {
  3663. // è un file
  3664. dataFile = [CCUtility dateDiff:metadata.date];
  3665. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3666. // Plist ancora da scaricare
  3667. if (metadata.cryptated && [metadata.title length] == 0) {
  3668. dataFile = @" ";
  3669. lunghezzaFile = @" ";
  3670. }
  3671. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:metadata.fileID activeAccount:app.activeAccount];
  3672. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3673. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3674. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3675. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3676. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3677. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3678. if (recordLocalFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3679. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3680. else
  3681. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3682. }
  3683. // Plist ancora da scaricare
  3684. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3685. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3686. cell.accessoryType = UITableViewCellAccessoryNone;
  3687. }
  3688. // ----------------------------------------------------------------------------------------------------------
  3689. // File Image View
  3690. // ----------------------------------------------------------------------------------------------------------
  3691. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3692. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3693. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3694. if (cell.fileImageView.image == nil) {
  3695. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3696. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3697. [app.icoImagesCache setObject:image forKey:metadata.fileID];
  3698. dispatch_async(dispatch_get_main_queue(), ^{
  3699. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3700. if (cell)
  3701. cell.fileImageView.image = image;
  3702. });
  3703. });
  3704. }
  3705. } else {
  3706. cell.fileImageView.image = [UIImage imageNamed:metadata.iconName];
  3707. if (metadata.thumbnailExists)
  3708. [self downloadThumbnail:metadata];
  3709. }
  3710. // ----------------------------------------------------------------------------------------------------------
  3711. // Image Status cyptated & Lock Passcode
  3712. // ----------------------------------------------------------------------------------------------------------
  3713. // File Cyptated
  3714. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3715. cell.statusImageView.image = [UIImage imageNamed:image_lock];
  3716. }
  3717. // Directory con passcode lock attivato
  3718. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:metadata.fileNameData];
  3719. if (metadata.directory && ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length])) cell.statusImageView.image = [UIImage imageNamed:image_passcode];
  3720. // ----------------------------------------------------------------------------------------------------------
  3721. // Offline
  3722. // ----------------------------------------------------------------------------------------------------------
  3723. BOOL isOfflineFile = [CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount];
  3724. if (isOfflineFile) {
  3725. if (metadata.cryptated) cell.offlineImageView.image = [UIImage imageNamed:image_offlinecrypto];
  3726. else cell.offlineImageView.image = [UIImage imageNamed:image_offline];
  3727. }
  3728. // ----------------------------------------------------------------------------------------------------------
  3729. // Share
  3730. // ----------------------------------------------------------------------------------------------------------
  3731. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3732. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3733. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3734. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3735. // Aggiungiamo il Tap per le shared
  3736. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3737. if (isShare) {
  3738. cell.sharedImageView.image = [UIImage imageNamed:image_shareConnect];
  3739. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3740. [tap setNumberOfTapsRequired:1];
  3741. cell.sharedImageView.userInteractionEnabled = YES;
  3742. [cell.sharedImageView addGestureRecognizer:tap];
  3743. }
  3744. if (isMounted) {
  3745. cell.sharedImageView.image = [UIImage imageNamed:image_shareMounted];
  3746. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3747. [tap setNumberOfTapsRequired:1];
  3748. cell.sharedImageView.userInteractionEnabled = YES;
  3749. [cell.sharedImageView addGestureRecognizer:tap];
  3750. }
  3751. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3752. if ([shareLink length] > 0) cell.sharedImageView.image = [UIImage imageNamed:image_shareLink];
  3753. if ([shareUserAndGroup length] > 0) cell.sharedImageView.image = [UIImage imageNamed:image_shareUser];
  3754. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3755. [tap setNumberOfTapsRequired:1];
  3756. cell.sharedImageView.userInteractionEnabled = YES;
  3757. [cell.sharedImageView addGestureRecognizer:tap];
  3758. }
  3759. } else {
  3760. cell.sharedImageView.userInteractionEnabled = NO;
  3761. }
  3762. // ----------------------------------------------------------------------------------------------------------
  3763. // downloadFile
  3764. // ----------------------------------------------------------------------------------------------------------
  3765. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3766. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusdownloadcrypto];
  3767. else cell.statusImageView.image = [UIImage imageNamed:image_statusdownload];
  3768. // sessionTaskIdentifier : RELOAD + STOP
  3769. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3770. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptaskcrypto] forState:UIControlStateNormal];
  3771. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptask] forState:UIControlStateNormal];
  3772. cell.cancelTaskButton.hidden = NO;
  3773. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3774. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3775. cell.reloadTaskButton.hidden = NO;
  3776. }
  3777. // sessionTaskIdentifierPlist : RELOAD
  3778. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3779. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3780. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3781. cell.reloadTaskButton.hidden = NO;
  3782. }
  3783. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3784. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3785. if (progress > 0) {
  3786. if (metadata.cryptated) cell.progressView.progressTintColor = COLOR_CRYPTOCLOUD;
  3787. else cell.progressView.progressTintColor = COLOR_TEXT_ANTHRACITE;
  3788. cell.progressView.progress = progress;
  3789. cell.progressView.hidden = NO;
  3790. }
  3791. // ----------------------------------------------------------------------------------------------------------
  3792. // downloadFile Error
  3793. // ----------------------------------------------------------------------------------------------------------
  3794. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3795. cell.statusImageView.image = [UIImage imageNamed:image_statuserror];
  3796. if ([metadata.sessionError length] == 0)
  3797. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3798. else
  3799. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3800. }
  3801. }
  3802. // ----------------------------------------------------------------------------------------------------------
  3803. // uploadFile
  3804. // ----------------------------------------------------------------------------------------------------------
  3805. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3806. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusuploadcrypto];
  3807. else cell.statusImageView.image = [UIImage imageNamed:image_statusupload];
  3808. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_removetaskcrypto] forState:UIControlStateNormal];
  3809. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_removetask] forState:UIControlStateNormal];
  3810. cell.cancelTaskButton.hidden = NO;
  3811. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3812. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3813. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3814. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusstopcrypto];
  3815. else cell.statusImageView.image = [UIImage imageNamed:image_statusstop];
  3816. cell.reloadTaskButton.hidden = NO;
  3817. cell.stopTaskButton.hidden = YES;
  3818. } else {
  3819. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptaskcrypto] forState:UIControlStateNormal];
  3820. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptask] forState:UIControlStateNormal];
  3821. cell.stopTaskButton.hidden = NO;
  3822. cell.reloadTaskButton.hidden = YES;
  3823. }
  3824. // se non c'è una preview in bianconero metti l'immagine di default
  3825. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3826. cell.fileImageView.image = [UIImage imageNamed:image_uploaddisable];
  3827. cell.labelTitle.enabled = NO;
  3828. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3829. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3830. if (progress > 0) {
  3831. if (metadata.cryptated) cell.progressView.progressTintColor = COLOR_CRYPTOCLOUD;
  3832. else cell.progressView.progressTintColor = COLOR_TEXT_ANTHRACITE;
  3833. cell.progressView.progress = progress;
  3834. cell.progressView.hidden = NO;
  3835. }
  3836. // ----------------------------------------------------------------------------------------------------------
  3837. // uploadFileError
  3838. // ----------------------------------------------------------------------------------------------------------
  3839. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3840. cell.labelTitle.enabled = NO;
  3841. cell.statusImageView.image = [UIImage imageNamed:image_statuserror];
  3842. if ([metadata.sessionError length] == 0)
  3843. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3844. else
  3845. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3846. }
  3847. }
  3848. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3849. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3850. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3851. return cell;
  3852. }
  3853. - (void)setTableViewFooter
  3854. {
  3855. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3856. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3857. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3858. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3859. UIFont *appFont = [UIFont systemFontOfSize:12];
  3860. footerLabel.font = appFont;
  3861. footerLabel.textColor = [UIColor grayColor];
  3862. footerLabel.backgroundColor = [UIColor clearColor];
  3863. footerLabel.textAlignment = NSTextAlignmentCenter;
  3864. NSString *folders;
  3865. NSString *files;
  3866. NSString *footerText;
  3867. if (_sectionDataSource.directories > 1) {
  3868. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3869. } else if (_sectionDataSource.directories == 1){
  3870. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3871. } else {
  3872. folders = @"";
  3873. }
  3874. if (_sectionDataSource.files > 1) {
  3875. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3876. } else if (_sectionDataSource.files == 1){
  3877. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3878. } else {
  3879. files = @"";
  3880. }
  3881. if ([folders isEqualToString:@""]) {
  3882. footerText = files;
  3883. } else if ([files isEqualToString:@""]) {
  3884. footerText = folders;
  3885. } else {
  3886. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3887. }
  3888. footerLabel.text = footerText;
  3889. [footerView addSubview:footerLabel];
  3890. [self.tableView setTableFooterView:footerView];
  3891. }
  3892. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3893. {
  3894. NSString *textMessage;
  3895. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3896. // se non può essere selezionata deseleziona
  3897. if ([cell isEditing] == NO)
  3898. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3899. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3900. if (self.tableView.editing) {
  3901. [self setTitle];
  3902. return;
  3903. }
  3904. // test crash
  3905. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3906. if (indexPath.row >= [metadatas count]) return;
  3907. // settiamo il record file.
  3908. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3909. //
  3910. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  3911. // se è in corso una sessione
  3912. if ([_metadata.session length] > 0) return;
  3913. if (_metadata.errorPasscode) {
  3914. // se UUID è nil lo sta ancora caricando quindi esci
  3915. if (!_metadata.uuid) return;
  3916. // esiste un hint ??
  3917. CCCrypto *crypto = [[CCCrypto alloc] init];
  3918. NSString *hint = [crypto getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3919. // qui !! la richiesta della nuova passcode
  3920. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3921. // stesso UUID ... la password è stata modificata !!!!!!
  3922. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3923. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3924. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3925. [alertView show];
  3926. } else {
  3927. // UUID diverso.
  3928. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3929. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3930. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3931. [alertView show];
  3932. }
  3933. // chiediamo la passcode e ricarichiamo tutto.
  3934. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3935. viewController.delegate = self;
  3936. viewController.fromType = CCBKPasscodeFromPasscode;
  3937. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3938. viewController.passcodeInputView.maximumLength = 64;
  3939. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3940. viewController.inputViewTitlePassword = NO;
  3941. viewController.title = _brand_;
  3942. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3943. viewController.navigationItem.leftBarButtonItem.tintColor = COLOR_CRYPTOCLOUD;
  3944. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3945. [self presentViewController:navigationController animated:YES completion:nil];
  3946. }
  3947. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3948. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3949. NSString* selector;
  3950. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  3951. else selector = selectorLoadPlist;
  3952. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3953. return;
  3954. }
  3955. // se il plist è caricato ed è un modello aprilo
  3956. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  3957. // file
  3958. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  3959. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3960. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3961. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3962. } else {
  3963. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3964. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3965. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3966. }
  3967. }
  3968. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3969. }
  3970. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3971. {
  3972. [self setTitle];
  3973. }
  3974. #pragma --------------------------------------------------------------------------------------------
  3975. #pragma mark ===== Offline Folder Cell =====
  3976. #pragma --------------------------------------------------------------------------------------------
  3977. - (void)offlineFolderGraphicsServerUrl:(NSString *)serverUrl animation:(BOOL)animation
  3978. {
  3979. BOOL cryptated = NO;
  3980. CCCellMain *cell;
  3981. for (NSString* fileID in _sectionDataSource.allRecordsDataSource) {
  3982. CCMetadata *recordMetadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3983. if (recordMetadata.directory == NO)
  3984. continue;
  3985. if ([[CCUtility stringAppendServerUrl:_serverUrl addServerUrl:recordMetadata.fileNameData] isEqualToString:serverUrl]) {
  3986. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:recordMetadata.fileID];
  3987. cell = (CCCellMain *)[self.tableView cellForRowAtIndexPath:indexPath];
  3988. cryptated = recordMetadata.cryptated;
  3989. break;
  3990. }
  3991. }
  3992. if (!cell)
  3993. return;
  3994. if (animation) {
  3995. NSURL *myURL;
  3996. if (cryptated)
  3997. myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  3998. else
  3999. myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  4000. cell.synchronizedImageView.image = [UIImage animatedImageWithAnimatedGIFURL:myURL];
  4001. } else {
  4002. cell.synchronizedImageView.image = nil;
  4003. }
  4004. }
  4005. #pragma --------------------------------------------------------------------------------------------
  4006. #pragma mark ===== Navigation ====
  4007. #pragma --------------------------------------------------------------------------------------------
  4008. - (BOOL)shouldPerformSegue:(NSString *)serverUrl
  4009. {
  4010. // if background return
  4011. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  4012. // se non siamo in primo piano o se non siamo nella stessa directory esci
  4013. if (self.view.window == NO || ([serverUrl isEqualToString:_serverUrl] == NO && serverUrl))
  4014. return NO;
  4015. // Collapsed ma siamo già in detail esci
  4016. if (self.splitViewController.isCollapsed)
  4017. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4018. // Video in esecuzione esci
  4019. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4020. return YES;
  4021. }
  4022. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4023. {
  4024. id viewController = segue.destinationViewController;
  4025. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4026. UINavigationController *nav = viewController;
  4027. _detailViewController = (CCDetail *)nav.topViewController;
  4028. } else {
  4029. _detailViewController = segue.destinationViewController;
  4030. }
  4031. NSMutableArray *allRecordsDataSourceImagesVideos = [[NSMutableArray alloc] init];
  4032. for (NSString *fileID in _sectionDataSource.allFileID) {
  4033. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4034. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4035. [allRecordsDataSourceImagesVideos addObject:metadata];
  4036. }
  4037. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4038. _detailViewController.metadataDetail = _metadataSegue;
  4039. _detailViewController.dateFilterQuery = nil;
  4040. _detailViewController.isCameraUpload = NO;
  4041. [_detailViewController setTitle:_metadata.fileNamePrint];
  4042. }
  4043. // can i go to next viewcontroller
  4044. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4045. {
  4046. NSString *nomeDir;
  4047. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4048. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  4049. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  4050. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4051. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4052. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4053. viewController.delegate = self;
  4054. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4055. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4056. viewController.inputViewTitlePassword = YES;
  4057. if ([CCUtility getSimplyBlockCode]) {
  4058. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4059. viewController.passcodeInputView.maximumLength = 6;
  4060. } else {
  4061. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4062. viewController.passcodeInputView.maximumLength = 64;
  4063. }
  4064. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:BKPasscodeKeychainServiceName];
  4065. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4066. viewController.touchIDManager = touchIDManager;
  4067. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4068. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4069. viewController.navigationItem.leftBarButtonItem.tintColor = COLOR_CRYPTOCLOUD;
  4070. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4071. [self presentViewController:navController animated:YES completion:nil];
  4072. return;
  4073. }
  4074. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4075. else nomeDir = _metadata.fileName;
  4076. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:nomeDir];
  4077. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4078. if (viewController.isViewLoaded == false) {
  4079. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4080. viewController.isFolderEncrypted = _metadata.cryptated;
  4081. viewController.serverUrl = serverUrlPush;
  4082. viewController.titleMain = _metadata.fileNamePrint;
  4083. viewController.textBackButton = _titleMain;
  4084. // save self
  4085. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4086. }
  4087. // OFF SearchBar
  4088. [viewController cancelSearchBar];
  4089. [self.navigationController pushViewController:viewController animated:YES];
  4090. }
  4091. }
  4092. @end