CCMain.m 250 KB

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