CCMain.m 257 KB

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