CCMain.m 250 KB

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