CCMain.m 257 KB

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