CCMain.m 255 KB

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