CCMain.m 254 KB

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