CCMain.m 251 KB

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